Reputation: 5269
I want to know how the typeof
and sizeof
keywords are implemented.
What if I want to implement my own 'x'of()
expression like timeof(object)
where object
contains a DateTime
as one of it's properties or something?
Upvotes: 5
Views: 198
Reputation: 56556
The short answer is no. typeof
and sizeof
are part of the C# language, and you cannot (directly) add expressions like them. The normal way of doing what you're asking would be to simply access the property:
DateTime time = myObject.SomeDateTimeProperty;
You could make a method to do this (although it wouldn't make sense for such a trivial thing). E.g. if you used an interface:
public interface ICreateTime
{
DateTime CreateTime { get; }
}
public DateTime TimeOf(ICreateTime myObject)
{
return myObject.CreateTime;
}
To be more specific: typeof
and sizeof
aren't implemented in the same way you implement methods. Instead, typeof
translates to ldtoken [type]
and call System.Type.GetTypeFromHandle
IL instructions, and sizeof
becomes a constant. E.g.
Type t = typeof(int);
int s = sizeof(int);
Compiles to:
IL_0001: ldtoken System.Int32
IL_0006: call System.Type.GetTypeFromHandle
IL_000B: stloc.0 // t
IL_000C: ldc.i4.4 // the constant 4, typed as a 4-byte integer
IL_000D: stloc.1 // s
Upvotes: 10
Reputation: 1496
For your use case, I would not recommend doing this even if it was possible.
typeof
and sizeof
are both methods that return information relevant to the compiler. Getting the time of an object is accessing a property and not a compiler attribute.
If you have an object that has a DateTime
you should be accessing it using:
object.DateTimeProperty
Upvotes: 1