Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are typeof and sizeof Implemented

Tags:

c#

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?

like image 429
Roman Ratskey Avatar asked Mar 14 '14 19:03

Roman Ratskey


People also ask

How is sizeof implemented?

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.

What is data type implementation?

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.

What is the size of an into data type?

The int and unsigned int types have a size of four bytes.


1 Answers

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
like image 164
Tim S. Avatar answered Sep 18 '22 04:09

Tim S.