Search code examples
c#variablestypesnew-operator

how to check whether a variable is a class or not in c#


I have a function that gets a object as a parameter

ex:

public static void doSomthingWithObject(object obj)
{
 (.....)
}

and I want to check whether the object I got is a class or a simple variable (e.g if it requires a constructor to create) and if so, I want to get all the properties of that object so the code will look something like that:

public static void doSomthingWithObject(object obj)
{
 if(objectIsClass())
  {
    object[] arr = obj.getAllPropeties
 (.....)
  }
  else
  {
 (.....)
  }
}

is that possible?

edit: people found my definition to class variables and simple variables confusing. to make it clear, "simple variable" is a variable that can hold only one value, and to access this value you need to simply write "= var" while "class variable" can hold multiple values (unless it has 1-0 properties), and each one of its values can be accessed using get ex: = obj.prop (unless there is no get) each value in this type of variable is held by a property, and to define a new class property the new keyword must be used


Solution

  • In C#, everything that you see is either a class or a struct, (Int is struct for example).

    So the question comes down to two things,

    1. Do you want to know all the types which do not have a parameterless constructor (like int doesn't have) To do that,

      bool ObjectIsClass(object o)
      {
         return  o.GetType().GetConstructor(new Type[0])!=null;
      }
      
    2. Do you want to Look for Primitive types

      bool IsPrimitive(object o)
      {
         return o.GetType().IsPrimitive;
      }