Object

Object  is a data type that can hold properties without explicitly defining a type like class. Object is reference type variable. So when you pass an object to a variable or a method, it references variable. This means when you change copied variable, it will change the main variable too. Or changing main variable will change the copied variable.

 

Let’s take a look at the following example to see the usage of anonymous Object,

 

using System;
using System.Reflection;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {

            Object obj = new { Name = "CSharp", Motto = "ZeroToCSharp" };

            string name = GetValueOfObject(obj, "Name");
            string motto = GetValueOfObject(obj, "Motto");

            //To print output
            Console.WriteLine(string.Concat("Obj: ", name, " ", motto));
            Console.ReadKey();
        }

        //Method to get object's property
        static string GetValueOfObject(Object obj, string propertyName) {
            if (obj == null)
                return null;

            Type type = obj.GetType();
            PropertyInfo propertyInfo = type.GetProperty(propertyName);
            Object property = propertyInfo.GetValue(obj, null);
            return property as string;
        }
    }
}

 

Output:

Obj: CSharp ZeroToCSharp

 

 

Let’s see if object is reference type variable.

 

using System;
using System.Reflection;

namespace ZeroToCSharp {
    class Program {
        static void Main(string[] args) {

            SampleClass sample1 = new SampleClass();
            sample1.Text = "OldText";

            object obj1 = sample1;
            object obj2 = obj1;

            sample1.Text = "NewText";

            string str1 = ((SampleClass)obj1).Text;
            string str2 = ((SampleClass)obj2).Text;

            Console.WriteLine(string.Concat("Text of obj1: ", str1));
            Console.WriteLine(string.Concat("Text of obj2: ", str2));
            Console.ReadKey();
        }
    }
    struct SampleClass {
        public string Text { get; set; }
    }
}

 

Output:

Text of obj1: OldText
Text of obj2: OldText

 

 

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x