I would like to the get the class that is being pointed to from an Object variable.
For instance, if I have an instance of a StringBuilder object that I subsequently set an Object variable to, can I somehow know that the Object variable points to a StringBuilder object?
Example:
StringBuilder sbText = New StringBuilder();
Object oMyObject = sbText;
// How can I determine that oMyObject points to an instance of StringBuilder object using only oMyObject
I have tried using typeof(oMyObject)
or oMyObject.GetType()
in every combination I can think of and still keep coming up with nothing more than Object
.
Seems like there should be a fairly straight forward way to do this and there probably is but I am not finding it.
I must disagree with the user who marked this as a duplicate question to the one they provided the link to. The title of my question may not have been as clear as it could have been (I have altered it a bit now) and the answers to both may involve the same method but the user who asked the other question was looking for a way to instantiate an object as the same type as another object. I was only looking for the way to get the name of a class when all I have is a variable of type Object. I would never have come up with the answer that Reed provided by looking at that question and I don't recall it ever coming up in a search on this site or a wider Google search.
GetType()
should provide the proper System.Type
of the object at runtime.
For example, this prints "StringBuilder"
:
StringBuilder sbText = new StringBuilder();
Object oMyObject = sbText;
Console.WriteLine(oMyObject.GetType().Name);
Note that if you just want to check for a specific class type, is
(or as
) often works more cleanly than getting a Type
:
StringBuilder sbText = new StringBuilder();
Object oMyObject = sbText;
//...
StringBuilder sb = oMyObject as StringBuilder;
if (sb != null)
{
// oMyObject was a StringBuilder - you can use sb as needed:
sb.AppendText("Foo");
}
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