Nikil
Nikil

Reputation: 369

Declaring an object which can be of any Type in c#

I am looking for an implementation similar to the type 'id' in objective c which can be of any type during runtime.Is it possible to do that in c#?

let me explain my requirement

id abc;// a common type which can hold any object during runtime
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 abc = opt1;
}
else if(cond2)
{
 Option2 opt2 = new Option2();
 abc = opt2;
}
...

How can I do the same in c# ? Thanks, Nikil.

Upvotes: 11

Views: 47558

Answers (5)

BoltClock
BoltClock

Reputation: 723498

Declare an object or use the dynamic keyword as others say, or if you know an interface or base class that all your possible objects derive from, use that type:

IOption abc;

Upvotes: 2

Stretto
Stretto

Reputation: 486

dynamic types are exactly for this purpose. Their "type" is dynamic(which obviously means at run-time).

I don't know about objective-C but it seems like id = dynamic.

Essentially a dynamic type is treated as a "typeless" object. There is no intellisense and no type checking done at compile time.

Upvotes: 4

Ian Mercer
Ian Mercer

Reputation: 39277

You have several choices to consider and var isn't one of them.

1) Make all you Option classes inherit from an abstract base class.

2) Make all your Option classes inherit from an Interface.

3) Use object as the type

4) Use a dynamic object

It depends on what you want to do with 'abc' after this point in the code.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564373

You can do this in two ways:

First, you can declare the type as object. This will allow you to assign anything to the type. Do be aware, however, that if you assign a value type to the object reference, it will be boxed.

For example:

object abc;
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 // Assignment works, but you can't call a method or prop. defined on Option1
 abc = opt1;
} // ...

The second option, which requires C# 4, is to declare it as dynamic. This will allow you to actually call methods and properties on the object as if it were the "real" type. The method call will fail at runtime if it does not exist, but succeed at compile time.

For example:

dynamic abc;
if(cond1)
{
 Option1 opt1 = new Option1();//opt1 is an object of user defined class Option1
 // Assignment works
 abc = opt1;

 // This will work if Option1 has a method Option1Method()!
 // If not, it will raise an exception at run time...
 abc.Option1Method(); 
} // ...

Upvotes: 17

gsharp
gsharp

Reputation: 27927

object abc; // :-)

or is it too simple?

Upvotes: 4

Related Questions