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.
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.
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.
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With