Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Accessing one of many possible objects passed to a function

Accessing one of many possible objects passed to a function

Scheduled Pinned Locked Moved C#
question
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    TNCaver
    wrote on last edited by
    #1

    My question is in the code comment below:

    public class MyBase
    {
    public string CommonProperty { get; set; }
    }

    public class ClassOne : MyBase
    {
    public string ClassOneProperty { get; set; }
    }

    public class ClassTwo : MyBase
    {
    public string ClassTwoProperty { get; set; }
    }

    public class program()
    {
    var classTwo = new ClassTwo();
    classTwo.CommonProperty = "Some string";
    classTwo.ClassTwoProperty = "Some other string";
    TestFunction(classTwo);

    private void TestFunction(object unknownClass)
    {
    // how do I convert unknownClass to its actual class and access its properties
    // regardless of which type was passed to the function?
    }
    }

    If you think 'goto' is evil, try writing an Assembly program without JMP.

    T M T L 4 Replies Last reply
    0
    • T TNCaver

      My question is in the code comment below:

      public class MyBase
      {
      public string CommonProperty { get; set; }
      }

      public class ClassOne : MyBase
      {
      public string ClassOneProperty { get; set; }
      }

      public class ClassTwo : MyBase
      {
      public string ClassTwoProperty { get; set; }
      }

      public class program()
      {
      var classTwo = new ClassTwo();
      classTwo.CommonProperty = "Some string";
      classTwo.ClassTwoProperty = "Some other string";
      TestFunction(classTwo);

      private void TestFunction(object unknownClass)
      {
      // how do I convert unknownClass to its actual class and access its properties
      // regardless of which type was passed to the function?
      }
      }

      If you think 'goto' is evil, try writing an Assembly program without JMP.

      T Offline
      T Offline
      Tony Hill
      wrote on last edited by
      #2

      You could use the 'as' operator to try and cast it to a known type, if the cast works then you know the object type.

      private static void TestFunction(object unknownClass)
      {
          ClassOne c1 = unknownClass as ClassOne;
      
          if (c1 != null)
          {
              Console.WriteLine("Object is a ClassOne object");
          }
          else
          {
              Console.WriteLine("Object is not a ClassOne object");
          }
      
          ClassTwo c2 = unknownClass as ClassTwo;
      
          if (c2 != null)
          {
              Console.WriteLine("Object is a ClassTwo object");
          }
          else
          {
              Console.WriteLine("Object is not a ClassTwo object");
          }
      }
      
      T 1 Reply Last reply
      0
      • T TNCaver

        My question is in the code comment below:

        public class MyBase
        {
        public string CommonProperty { get; set; }
        }

        public class ClassOne : MyBase
        {
        public string ClassOneProperty { get; set; }
        }

        public class ClassTwo : MyBase
        {
        public string ClassTwoProperty { get; set; }
        }

        public class program()
        {
        var classTwo = new ClassTwo();
        classTwo.CommonProperty = "Some string";
        classTwo.ClassTwoProperty = "Some other string";
        TestFunction(classTwo);

        private void TestFunction(object unknownClass)
        {
        // how do I convert unknownClass to its actual class and access its properties
        // regardless of which type was passed to the function?
        }
        }

        If you think 'goto' is evil, try writing an Assembly program without JMP.

        M Offline
        M Offline
        Mycroft Holmes
        wrote on last edited by
        #3

        GetType() will return the object name

        	static void TestFunction(object unknownClass)
        	{
        		string sType = unknownClass.GetType().ToString();
        		Console.WriteLine(sType);
        		Console.ReadLine();
        	}
        

        Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

        T 1 Reply Last reply
        0
        • T TNCaver

          My question is in the code comment below:

          public class MyBase
          {
          public string CommonProperty { get; set; }
          }

          public class ClassOne : MyBase
          {
          public string ClassOneProperty { get; set; }
          }

          public class ClassTwo : MyBase
          {
          public string ClassTwoProperty { get; set; }
          }

          public class program()
          {
          var classTwo = new ClassTwo();
          classTwo.CommonProperty = "Some string";
          classTwo.ClassTwoProperty = "Some other string";
          TestFunction(classTwo);

          private void TestFunction(object unknownClass)
          {
          // how do I convert unknownClass to its actual class and access its properties
          // regardless of which type was passed to the function?
          }
          }

          If you think 'goto' is evil, try writing an Assembly program without JMP.

          T Offline
          T Offline
          TNCaver
          wrote on last edited by
          #4

          What I'm trying to do is avoid duplicating code to access/manipulate the common properties. In TestFunction I want to be able to take unknownObject, cast it to its actual class type, and display or change its properties. Something like the following (which won't build):

          private void TestFunction(object unknownClass)
          {
          var localObject = null;
          string specificProperty = string.empty;

          switch (unknownObject.GetType().Name)
          {
          case "ClassOne":
          localObject = (ClassOne)unknownObject;
          specificProperty = object.ClassOneProperty;
          break;
          case "ClassTwo":
          localObject = (ClassTwo)unknownObject;
          specificProperty = object.ClassTwoProperty;
          break;
          }

          Console.PrintLine($"Common Property = {localObject.CommonProperty}, Specific Property = {specificProperty}.");
          }

          If you think 'goto' is evil, try writing an Assembly program without JMP.

          M Richard DeemingR 2 Replies Last reply
          0
          • T Tony Hill

            You could use the 'as' operator to try and cast it to a known type, if the cast works then you know the object type.

            private static void TestFunction(object unknownClass)
            {
                ClassOne c1 = unknownClass as ClassOne;
            
                if (c1 != null)
                {
                    Console.WriteLine("Object is a ClassOne object");
                }
                else
                {
                    Console.WriteLine("Object is not a ClassOne object");
                }
            
                ClassTwo c2 = unknownClass as ClassTwo;
            
                if (c2 != null)
                {
                    Console.WriteLine("Object is a ClassTwo object");
                }
                else
                {
                    Console.WriteLine("Object is not a ClassTwo object");
                }
            }
            
            T Offline
            T Offline
            TNCaver
            wrote on last edited by
            #5

            Thank you, Tony. I'm trying to avoid duplicating code that accesses the properties common to all the objects passed to TestFunction. If you have a moment, please see my clarification in this thread.

            If you think 'goto' is evil, try writing an Assembly program without JMP.

            1 Reply Last reply
            0
            • M Mycroft Holmes

              GetType() will return the object name

              	static void TestFunction(object unknownClass)
              	{
              		string sType = unknownClass.GetType().ToString();
              		Console.WriteLine(sType);
              		Console.ReadLine();
              	}
              

              Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

              T Offline
              T Offline
              TNCaver
              wrote on last edited by
              #6

              Thank you, Mycroft. I did know about getting the name and type, but that only gets me part way there. I'm trying to avoid duplicating code that accesses the properties common to all the objects passed to TestFunction. If you have a moment, please see my clarification in this thread.

              If you think 'goto' is evil, try writing an Assembly program without JMP.

              1 Reply Last reply
              0
              • T TNCaver

                What I'm trying to do is avoid duplicating code to access/manipulate the common properties. In TestFunction I want to be able to take unknownObject, cast it to its actual class type, and display or change its properties. Something like the following (which won't build):

                private void TestFunction(object unknownClass)
                {
                var localObject = null;
                string specificProperty = string.empty;

                switch (unknownObject.GetType().Name)
                {
                case "ClassOne":
                localObject = (ClassOne)unknownObject;
                specificProperty = object.ClassOneProperty;
                break;
                case "ClassTwo":
                localObject = (ClassTwo)unknownObject;
                specificProperty = object.ClassTwoProperty;
                break;
                }

                Console.PrintLine($"Common Property = {localObject.CommonProperty}, Specific Property = {specificProperty}.");
                }

                If you think 'goto' is evil, try writing an Assembly program without JMP.

                M Offline
                M Offline
                Mycroft Holmes
                wrote on last edited by
                #7

                But you are not changing the common property in your example (except it may be because it is an example). Once you have the type I think there is something like String s = (unknownobject As ClassOne).CommonProperty

                Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

                T 1 Reply Last reply
                0
                • M Mycroft Holmes

                  But you are not changing the common property in your example (except it may be because it is an example). Once you have the type I think there is something like String s = (unknownobject As ClassOne).CommonProperty

                  Never underestimate the power of human stupidity - RAH I'm old. I know stuff - JSOP

                  T Offline
                  T Offline
                  TNCaver
                  wrote on last edited by
                  #8

                  Okay, maybe I can work with that. Thanks.

                  If you think 'goto' is evil, try writing an Assembly program without JMP.

                  1 Reply Last reply
                  0
                  • T TNCaver

                    My question is in the code comment below:

                    public class MyBase
                    {
                    public string CommonProperty { get; set; }
                    }

                    public class ClassOne : MyBase
                    {
                    public string ClassOneProperty { get; set; }
                    }

                    public class ClassTwo : MyBase
                    {
                    public string ClassTwoProperty { get; set; }
                    }

                    public class program()
                    {
                    var classTwo = new ClassTwo();
                    classTwo.CommonProperty = "Some string";
                    classTwo.ClassTwoProperty = "Some other string";
                    TestFunction(classTwo);

                    private void TestFunction(object unknownClass)
                    {
                    // how do I convert unknownClass to its actual class and access its properties
                    // regardless of which type was passed to the function?
                    }
                    }

                    If you think 'goto' is evil, try writing an Assembly program without JMP.

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #9

                    string s1, s2;

                    if ( unknownClass is MyBase myBase ) {

                    s1 = myBase.CommonProperty;

                    if ( unknownClass is ClassOne one ) {
                    s2 = one.ClassOneProperty;

                    } else if ( unknownClass is ClassTwo two ) {
                    s2 = two.ClassTwoProperty;
                    }
                    }

                    "Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I

                    1 Reply Last reply
                    0
                    • T TNCaver

                      What I'm trying to do is avoid duplicating code to access/manipulate the common properties. In TestFunction I want to be able to take unknownObject, cast it to its actual class type, and display or change its properties. Something like the following (which won't build):

                      private void TestFunction(object unknownClass)
                      {
                      var localObject = null;
                      string specificProperty = string.empty;

                      switch (unknownObject.GetType().Name)
                      {
                      case "ClassOne":
                      localObject = (ClassOne)unknownObject;
                      specificProperty = object.ClassOneProperty;
                      break;
                      case "ClassTwo":
                      localObject = (ClassTwo)unknownObject;
                      specificProperty = object.ClassTwoProperty;
                      break;
                      }

                      Console.PrintLine($"Common Property = {localObject.CommonProperty}, Specific Property = {specificProperty}.");
                      }

                      If you think 'goto' is evil, try writing an Assembly program without JMP.

                      Richard DeemingR Offline
                      Richard DeemingR Offline
                      Richard Deeming
                      wrote on last edited by
                      #10

                      Which version of C# / Visual Studio are you using?

                      private void TestFunction(object unknownClass)
                      {
                      (MyBase localObject, string specificProperty) = unknownClass switch
                      {
                      ClassOne c1 => (c1, c1.ClassOneProperty),
                      ClassTwo c2 => (c2, c2.ClassTwoProperty),
                      MyBase b => (b, null),
                      _ => (null, null),
                      };

                      if (localObject is null)
                      {
                          Console.WriteLine($"Unknown object: {unknownClass}");
                      }
                      else
                      {
                          Console.WriteLine($"Common Property = {localObject.CommonProperty}, Specific Property = {specificProperty}.");
                      }
                      

                      }


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups