How to know in C# code which type a variable was declared with
c#, declaration, types
Solution
See code below for example. The key is to use Generics, extension method was used just for nice syntax.
using System;
static class Program
{
public static Type GetDeclaredType<T>(this T obj)
{
return typeof(T);
}
// Demonstrate how GetDeclaredType works
static void Main(string[] args)
{
ICollection iCollection = new List<string>();
IEnumerable iEnumerable = new List<string>();
IList<string> iList = new List<string>();
List<string> list = null;
Type[] types = new Type[]{
iCollection.GetDeclaredType(),
iEnumerable.GetDeclaredType(),
iList.GetDeclaredType(),
list.GetDeclaredType()
};
foreach (Type t in types)
Console.WriteLine(t.Name);
}
}
Result:
ICollection
IEnumerable
IList`1
List`1
EDIT: You may also avoid using extension method here, as it would cause it to appear on every IntelliSense drop-down list. See another example:
using System;
using System.Collections;
static class Program
{
public static Type GetDeclaredType<T>(T obj)
{
return typeof(T);
}
static void Main(string[] args)
{
ICollection iCollection = new List<string>();
IEnumerable iEnumerable = new List<string>();
Type[] types = new Type[]{
GetDeclaredType(iCollection),
GetDeclaredType(iEnumerable)
};
foreach (Type t in types)
Console.WriteLine(t.Name);
}
}
also produces correct results.
Problem
I want to have some function that would return "Base" if a variable of class `Base` was passed to it, "Derived" if it was declared as `Derived`, etc. Not depending on runtime type of a value it was assigned to.