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?
To use the sizeof(), we can take the value using a variable x, using &x, it will print the address of it. Now if we increase the value of &x then it may increase in different way. If only one byte is increased, that means it is character, if the increased value is 4, then it is int or float and so on.
It is a set of rules about what kind of information can be represented by a variable in the language, and the transformations that apply to those types of information. It is implemented in the compiler or interpretter of the language.
The int and unsigned int types have a size of four bytes.
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
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