Object variables in C#

JohnCTX 636 Reputation points
2021-01-23T17:51:42.583+00:00

Is there such a thing as an object variable in C#, and if it is, then how should users pass them on to functions as parameters?

Can users provide me some examples?

Regards,

JohnCTX

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,911 questions
Universal Windows Platform (UWP)
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,128 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,461 Reputation points
    2021-01-23T21:44:32.12+00:00

    Since others have covered the basics I would add it's best to use strong type parameters rather than a base object. Then using a plain object you would then need to first check it's underlying type then cast it.

    Below is the tip of the iceberg.

    Example, I want a list of employees and managers in a list.

    We start off with a base class person

    public class Person : IPerson  
    {  
        public int Id { get; set; }  
        public string FirstName { get; set; }  
        public string LastName { get; set; }  
        public DateTime HireDate { get; set; }  
        public string FullName => $"{FirstName} {LastName}";  
        public override string ToString() => $"{Id} {FullName}";  
    }  
    

    Employee class which inherits Person

    public class Employee : Person  
    {  
        public int ReportsTo { get; set; }  
    }  
    

    Mock them up into a single list

    public class Mocked  
    {  
        public static List<Person> PeopleList()  
        {  
            var employees = new List<Employee>()  
            {  
                new() {Id = 1, FirstName = "Joe", LastName = "Jones", HireDate = new DateTime(2018,12,1), ReportsTo = 5},  
                new() {Id = 2, FirstName = "Mary", LastName = "Smith", HireDate = new DateTime(2018,9,1), ReportsTo = 5},  
                new() {Id = 3, FirstName = "Nancy", LastName = "Ravioli", HireDate = new DateTime(2017,4,12), ReportsTo = 6},  
                new() {Id = 4, FirstName = "Andrew", LastName = "Fuller", HireDate = new DateTime(2019,7,2), ReportsTo = 6},  
                new() {Id = 7, FirstName = "Steven", LastName = "Buchanan", HireDate = new DateTime(2015,5,16), ReportsTo = 5},  
                new() {Id = 9, FirstName = "Karen", LastName = "Stone", HireDate = new DateTime(2020,5,16), ReportsTo = 8}  
            };  
      
            var people = new List<Person>()  
            {  
                new Manager() {Id = 5, FirstName = "Anne", LastName = "Wordsworth",   
                    HireDate = new DateTime(2015,7,2), YearsAsManager = 3,Employees = employees.Take(2).ToList()},  
                new Manager() {Id = 6, FirstName = "Bob", LastName = "Gallagher",   
                    HireDate = new DateTime(2014,7,2), YearsAsManager = 4,Employees = employees.Skip(2).Take(2).ToList()},  
                new Manager() {Id = 8, FirstName = "Michael", LastName = "Suyama",  
                    HireDate = new DateTime(2014,7,2), YearsAsManager = 1,Employees = employees.Skip(employees.Count -1).Take(1).ToList()}  
            };  
      
            people.AddRange(employees);  
      
            return people;  
        }  
    }  
    

    Then say in a form declare a list of Person

    private readonly List<Person> _peopleList;  
    

    In form load event load the list using the mocked data above.

    _peopleList = Mocked.PeopleList();  
    

    Then check types

    foreach (Person person1 in _peopleList)  
    {  
        if (person1 is Manager person)  
        {  
            _stringBuilder.AppendLine(person.FullName);  
        }  
    }  
    

    Other ideas, use generics e.g.

    namespace ExtensionsLibrary  
    {  
        public static class GenericExtensions  
        {  
      
            public static bool IsPositive<T>(this T value) where T : struct, IComparable<T> =>  
                value.CompareTo(default(T)) > 0;  
      
        }  
    }  
    

    Usage on int a and decimal

    decimal someDecimal = 1.4m;  
    int someInt = 3;  
      
    if (someDecimal.IsPositive())  
    {  
          
    }  
      
    if (someInt.IsPositive())  
    {  
          
    }  
    

    Then if all elements are the same why use object e.g. (where sampleArray might be passed as a parameter)

    Type type = typeof(string);  
    object[] sampleArray = { "Hello", "C#" };  
      
    var destinationArray = Array.CreateInstance(type, sampleArray.Length);  
    Array.Copy(sampleArray, destinationArray, sampleArray.Length);  
    

    Look at param arrays.

    Then finally pattern matching

    foreach (var o in sampleArray)  
    {  
        switch (o)  
        {  
            case string s:  
                Console.WriteLine($"o is a string with value of {s}");  
                break;  
            case int i:  
                Console.WriteLine($"o is a int with value of {i}");  
                break;  
            case bool b:  
                Console.WriteLine($"Bool {b}");  
                break;  
        }  
    }  
    
    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Ken Tucker 5,856 Reputation points
    2021-01-23T18:36:40.697+00:00

    There is an Object type you can use.

      object myObject = new object();
    

    You can use it like so in a function parameter

        private bool MyFunction(object myInput)
        {
    

    Keep in mind object is the base class for everything so you pass anything in as an object

    0 comments No comments

  2. Castorix31 86,316 Reputation points
    2021-01-23T18:41:20.27+00:00

    You can see MSDN docs :
    The object type
    Boxing and Unboxing
    ...

    0 comments No comments

  3. Abdulhakim M. Elrhumi 356 Reputation points
    2021-01-23T20:45:31.507+00:00

    Hi

     public void Userlogin()
            {
              cls_Users user=new cls_Users();
              user =  usercmd.GetByUsernameAndPassWord(txtUserName.Text, HelperClass.EncryptPassword(txtPassword.Text));
              if (user.UserName != null)
              {
    
                Hide();
                MDIToolbarForm frm = new MDIToolbarForm();
                frm.tSLUserName.Text = user.UserName.ToString();
    
                frm.Show();
              }
    
              else
              {
                count++;
                XtraMessageBox.Show(HelperClass.EncryptPassword(txtPassword.Text));
                XtraMessageBox.Show("تأكد من أسم المستخدم وكلمة المرور", "دخول", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                HelperClass.ClearValues(tableLayoutPanel2);
                txtUserName.Focus();
              }
              if (count == 3)
              {
                Application.Exit();
              }
      }
    

    //See other code

     public static void StartOperation(Form frm)
            {
                frm.Cursor = Cursors.WaitCursor;
                frm.Enabled = false;
            }
    

    Best Regards.
    Please remember to mark the replies as answers if they help.

    0 comments No comments

  4. Duane Arnold 3,216 Reputation points
    2021-01-23T20:54:26.507+00:00

    Everything in .NET, an OO language platform, derives form System.Object the base object for all objects.

    https://learn.microsoft.com/en-us/dotnet/api/system.object?view=net-5.0

    https://www.guru99.com/c-sharp-variables-operator.html

    <copied>

    A variable is a name given to a storage area that is used to store values of various data types. Each variable in C# needs to have a specific type, which determines the size and layout of the variable's memory.

    <end>

    https://www.tutorialsteacher.com/csharp/csharp-data-types

    Primitive type string object has its System.String class as an example as does all .NET objects have a defined 'type' with 'type' being a class the blueprint that an object is derived from with System.Object being the base class/object for all .NET classes/objects.

    https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-5.0

    string strvariable = "help";

    The you can use either Object or string to pass strvariable as a parm to a method() or to a class constructor.

    private bool MyFunction(object obj)
    {
    string strvariable = (string) obj; 'you must cast the base object to the type
    it contains.
    }

    private bool MyFunction(string strvariablepassed )
    {

    string strvariable = strvariablepassed 'the type is known "string"
    }

    It's OO 101 for OO language platforms .NET, Java or whatever else that uses OO.

    https://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.