iltelko
iltelko

Reputation: 57

How to use reflection to handle all types?

I was trying to do many utility functions like this:

public bool HasMember(object obj, string name)
{
etc.
}

The name and meaning of this particular utility function are not relevant.

Unfortunately, the function above cannot handle all types, like DateTime or Decimal which are structs. It handles integers and custom objects well. I understand that c# have both structs and objects, and struct is not an object. But how can I handle all the types in my utility method? It is preferable that there are no overloaded methods because there are so many utility functions needed.

Previous Research:

The language reference did not give me advice: https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/using-structs

Also no help with the text explaining the value types: https://learn.microsoft.com/en-us/dotnet/articles/csharp/language-reference/keywords/value-types

Upvotes: 0

Views: 140

Answers (2)

Sweeper
Sweeper

Reputation: 273860

It can handle all types. object works like a "wildcard". Just pass your DateTime in!

It does, however, cause boxing when you pass a value type (structs like DateTime). Boxing is basically wrapping a value type into a reference type. This may or may not cause problems.

If you don't want boxing, consider generics:

public bool HasMember<T>(T obj, string name)
{

}

Upvotes: 2

CodeFuller
CodeFuller

Reputation: 31312

In C# value of any type, no matter class or struct, could be assigned to Object variable. These are the valid constructs:

object obj = new DateTime();
object obj2 = 100m;

So if your utility method has signature as you specified

public bool HasMember(object obj, string name)

you could call it both on classes and structs, like DateTime and Decimal.

Upvotes: 2

Related Questions