Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

oop

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.

like image 848
Nikil Avatar asked Jan 13 '11 19:01

Nikil


People also ask

Is there any object in C?

In terms of C programming, an object is implemented as a set of data members packed in a struct , and a set of related operations. With multiple instances, the data for an object are replicated for each occurrence of the object.

Which is the means of declaring a new object from a class?

Answer: A constructor is a special kind of subroutine in a class. It has the same name as the name of the class, and it has no return type, not even void. A constructor is called with the new operator in order to create a new object.

How do you declare an object variable?

You declare a variable of the Object Data Type by specifying As Object in a Dim Statement. You assign an object to such a variable by placing the object after the equal sign ( = ) in an assignment statement or initialization clause.

Can C be object-oriented?

C is a Procedural Oriented language. It does not support object-oriented programming (OOP) features such as polymorphism, encapsulation, and inheritance programming. C++ is both a procedural and an object-oriented programming language.


2 Answers

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;
like image 139
BoltClock Avatar answered Sep 30 '22 05:09

BoltClock


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.

like image 30
Stretto Avatar answered Sep 30 '22 05:09

Stretto