Burdock
Burdock

Reputation: 1105

Getting type of field (none instance)

Can I get the type of a field? Type.GetType(); only returns the type of an instance, so if field is set null I cant get the Type.

Note: I would prefer not using reflections~

Upvotes: 0

Views: 103

Answers (4)

Angel
Angel

Reputation: 3765

Why not just ask if is null ?

if (Type != null)
{
    return Type.GetType().Name;
}
else
{
    return "";
}

Upvotes: 0

user817530
user817530

Reputation:

public class test
{
    private int fTestInt;
    private string fTestString;
}

You can achieve getting the field type by typing fTestInt.GetType().

If you want a quick type validation you can use.

if (fTestInt is int)
{
    Console.Write("I'm an int!");
}

Not sure if this is what you're asking. Your question seems partial.

Upvotes: 0

Mike Zboray
Mike Zboray

Reputation: 40818

It's not clear whether you only want the compile time type when the field is null. A simple method like this could work:

public static class ReflectionExtensions
{
    public static Type GetCompileTimeType<T>(this T obj)
    {
        return typeof(T);
    }
}

You could modify it it check for null and return the actual type if that is what you want.

usage:

class A { }
class B : A { }

class C 
{
    private A a1, a2;
    public C()
    {
       a2 = new B();
       Console.WriteLine(a1.GetCompileTimeType()); // null but prints A
       Console.WriteLine(a2.GetCompileTimeType()); // actually a B but prints A
    }
}

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Depending on context GetProperty and PropertyType may work for you. I.e. if you have object type and property name:

var typeOfLength = typeof(String).GetProperty("Length").PropertyType;

Upvotes: 1

Related Questions