using System;
interface IAnimal
{
}
class Cat: IAnimal
{
}
class Program
{
public static void Main(string[] args)
{
IAnimal cat = new Cat();
// Console.WriteLine(cat.GetType());
// This would only give me the type of
// the backing store, i.e. Cat. Is there a
// way I can get to know that the identifier
// cat was declared as IAnimal?
Console.ReadKey();
}
}
Update: Thanks to Dan Bryant for the reminder.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
namespace TypeInfo
{
class Program
{
public static void Main(string[] args)
{
IAnimal myCat = new Cat();
ReflectOnType();
Console.ReadKey();
}
public static void ReflectOnType()
{
Assembly.GetExecutingAssembly().
GetType("TypeInfo.Program").
GetMethod("Main",
BindingFlags.Static| BindingFlags.Public).
GetMethodBody().LocalVariables.
ToList().
ForEach( l => Console.WriteLine(l.LocalType));
}
}
interface IAnimal { }
class Cat : IAnimal { }
}
The reference o is of type Object . The object that it references is of type Integer . So the "reference type" would be Object and the "object type" would be Integer . What makes this confusing is that there's the (standardized, official) term "reference type" that encapsulates types that can be referenced.
Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.
A reference is an entity which provides a way to access object of its type. An object is an entity which provides a way to access the members of it's class or type. Generally, You can't access an object without a reference to it.
The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.
You can use generic type inference:
using System;
internal interface IAnimal
{
}
internal class Cat : IAnimal
{
}
class Program
{
static void Main()
{
var cat = new Cat();
Console.WriteLine(cat.GetType()); // Cat
Console.WriteLine(GetStaticType(cat)); // Cat
IAnimal animal = cat;
Console.WriteLine(GetStaticType(animal)); // IAnimal
}
static Type GetStaticType<T>(T _)
{
return typeof (T);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With