Solution
You cannot make a switch on a System.Type
and also you cannot do a typeof
on a variable.
What you can do is this:
static Dictionary<Type, TypeEnum> Types = new Dictionary<Type, TypeEnum>() { { typeof(TypeA), TypeEnum.TypeA } }; // Fill with more key-value pairs
enum TypeEnum
{
TypeA
// Fill with types
}
public static void Log<T>(T log)
{
TypeEnum type;
if (Types.TryGetValue(typeof(T), out type)) {
switch (type)
{ ... }
}
}
It's also the fastest solution which i know. Dictionary lookups are very fast. You could also do this with a System.String
( via Type.Name
or Type.FullName
) but it'll be slower because the string methods for Equals
( sure ) and for GetHashCode
( depending on their implementation ) are slower.
When you would use a String instead, it's the same what the compiler does when working with switch on a String.
switch(typeof(T).FullName) // Converted into a dictionary lookup
{ ... }
More thoughts
Depending on what you want to archive you should know that you also can use constraints:
public interface ILogItem
{
String GetLogData();
LogType LogType { get; }
}
public void Log<T>(T item)
where T : ILogItem
{
Debug.WriteLine(item.GetLogData());
// Read more data
switch (item.LogType)
{ ... }
}