1

this is my code:

bool ch=Type.IsBuiltIn("System.Int32");   // not working-> syntax error


public static class MyExtentions
    {             
        public static bool IsBuiltIn(this Type t, string _type)
        {
            return (Type.GetType(_type) == null) ? false : true;
        }
    }

Please I want Extend Type Class by IsBuiltIn new method

Islam Ibrahim
  • 85
  • 1
  • 9
  • You don't need extension method here – Sriram Sakthivel Aug 30 '13 at 11:01
  • write `typeof(int).IsBuiltIn` to your editor. What do you see? – I4V Aug 30 '13 at 11:03
  • the string you pass to the IsBuiltIn() method should be assembly-qualified name of the type. I mean you should pass System.Int32 insted of just int – Dimitri Aug 30 '13 at 11:05
  • "int" just isn't a built-in type. It is an *alias* that's specific to the C# compiler. Other languages use other aliases, like "Integer" in VB.NET. Given that there just a handful of aliases (don't forget the nullable ones), you can hardcode their names. Or just not do this. – Hans Passant Aug 30 '13 at 11:14
  • When does the `IsBuiltIn` return false? – shahkalpesh Aug 30 '13 at 11:19
  • A method such as `IsBuiltIn` doesn’t really make sense in an extensible type system. What do you need this for? Also, writing `someCondition ? false : true` makes no sense. Just write `!someCondition`. – Konrad Rudolph Aug 30 '13 at 11:21

3 Answers3

6

You can't have static extension methods. Your extension method works on an instance of the Type class, so to call it you'd have to do something like this:

typeof(Type).IsBuiltIn("System.Int32")

The workaround for this is to just put your extension method in a utility class, e.g. like the following, and call it like a normal static function:

public static class TypeExt
{             
    public static bool IsBuiltIn(string _type)
    {
        return Type.GetType(_type) == null;
    }
}

// To call it:
TypeExt.IsBuiltIn("System.Int32")

By the way, I don't think this will tell you whether the type is "built-in"; it will merely tell you whether a type with the given name has been loaded into the process.

Magnus Grindal Bakken
  • 2,083
  • 1
  • 16
  • 22
3

Extension methods are intended to describe new APIs on instances, not types. In your case, that API would be something like:

Type someType = typeof(string); // for example
bool isBuiltIn = someType.IsBuiltIn("Some.Other.Type");

which... clearly isn't what you wanted; the type here adds nothing and is not related to the IsBuiltIn. There is no compiler trick for adding new static methods to existing types, basically - so you will not be able to use Type.IsBuiltIn("Some.Other.Type").

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

You can't extend the Type class. You need an instance of the class to create an extension method.

Edit: See here and here.

Community
  • 1
  • 1
Loetn
  • 3,832
  • 25
  • 41