I am a little confused as to the use of the keyword "object" using in C#. What can and can't it be used for. Can you access a member?
C# is by default a statically typed language. That is, if you have an expression of a particular compile-time type you may access only the members of that type. This is a safety system; it is saying "I only have a guarantee that the members of this type are available, so prevent me from accessing any other members".
If you have an expression of type object
then you may access the members of object
-- ToString
, GetType
and so on.
If you want to turn off this safety system, use dynamic
instead of object
, and you can then call any member you like; if you call a member that does not exist, your program will crash. When you turn off a safety system the safety system is turned off and you become responsible for guaranteeing safety.
CLARIFICATION: Commenter Brian correctly points out that in the specific case of JSON objects, the default behaviour of a bad dynamic member access is to produce null rather than crashing; of course, much of the time after producing null because a member is unexpectedly missing, the next thing that will happen is a null dereference crash, so there's actually not a whole lot of additional safety margin there, but there is at least some.
My question to you was:
If you call GetType().ToString()
on the object, what do you get?
The answer was Newtonsoft.Json.Linq.JObject
. So in this case you can access the members of that type like this:
JObject jo = (JObject)testObject;
(Assuming you have using Newtonsoft.Json.Linq;
in your directives.)
Again, your program will crash if the object is not actually of that type.
You can do a safe type test with:
if (testObject is JObject jo)
{
var r = jo.Root;
...
I am trying to avoid making dozens of classes.
C# is a statically-typed language; it encourages creation of classes. Again, this is a safety system. Invest in its correct usage!
GetType().ToString()
on the object, what do you get?I am trying to avoid making dozens of classes
is the opposite mindset of what you should have. More often than not, you want more classes.