Steve
Steve

Reputation: 93

C# type of enclosing class

Is there some way to specify the type of the enclosing class declaration statically? If i had an instance, I could clearly use typeof(this), but statically I don't see a way.

Something like (where this_type is a placeholder):

public class Message
{
   public static readonly int SizeInBytes = Marshal.SizeOf(typeof(this_type));
}

Clearly, I could just use the actual type name, but I've got several classes that follow this pattern and would like something less copy/paste error prone.

Upvotes: 2

Views: 478

Answers (5)

Daniel Stone
Daniel Stone

Reputation: 276

After a short google search, I've seen other people using reflection to accomplish what you are talking about, but that comes with the caveat that it is probably a lot more expensive than just typing out typeof(this_type). I'd sooner recommend just typing it out.

Type t = MethodBase.GetCurrentMethod().DeclaringType

.NET: Determine the type of “this” class in its static method

Upvotes: 0

Caverna
Caverna

Reputation: 450

Perhaps:

public class Message
{
   public static readonly int SizeInBytes = Marshal.SizeOf(typeof(Message));
}

This way, 'Message' can also be static.

Upvotes: 1

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

You can use MethodBase.GetCurrentMethod().DeclaringType but typeof(Message) is probably the cleaner way

public class  Message
{
   public static readonly int SizeInBytes = Marshal.SizeOf(MethodBase.GetCurrentMethod().DeclaringType);
}

Btw, you'll get a runtime exception when you execute this code as it is trying to get the size of a managed object.

Upvotes: 3

Igor
Igor

Reputation: 62213

What about an extension method on the type and get it dynamically instead of pushing it to a readonly static variable?

public static class Extensions
{
   public static int SizeOfType(this System.Type tp) {
      return Marshal.SizeOf(tp);
   }

  public static int SizeOfObjectType(this object obj) {
      return obj.GetType().SizeOfType();
   }

}

// calling it from a method, 2 ways
var size1 = this.GetType().SizeOfType();
var size2 = this.SizeOfObjectType();
var size3 = typeof(string).SizeOfType();
var size4 = "what is my type size".SizeOfObjectType();

Upvotes: 0

Chris Disley
Chris Disley

Reputation: 1345

typeof(Message) would be the closest you'd get here, but I think you'd need to use a struct rather than a class to do this from what I recall.

Upvotes: 1

Related Questions