Type as a method parameter

BitSmithy 1,751 Reputation points
2020-06-09T13:17:25.847+00:00

I am trying such code, but this code is marked by VS as error. I want to pass class as a parameter to the method. Is any way to do it properly?

public string MyMethod(Object dataObject, Type dataType)
{

        if (dataObject is dataType obj)
        {
        //some code here

        }
    }
Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Matt Lacey 791 Reputation points MVP
    2020-06-09T13:26:44.343+00:00

    You could use a generic method for this:

    public string MyMethod<T>(T dataObject)
    {
        // some code here
    }
    

    The type is passed as T and (under the hood) the compiler creates appropriate overloads for you to pass what need.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Daniele 1,996 Reputation points
    2020-06-09T13:46:46.81+00:00

    It seems to me that you have to check if dataObject is of the given dataType at runtime , so I would go like that

    public string MyMethod(object dataObject, Type dataType)
    {
        if (dataType.IsInstanceOfType(dataObject))
        {
            //some code here
        }
    }
    

  2. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-06-16T16:48:29.623+00:00

    Hi, the construct "if (dataObject is dataType obj)" assume that "obj" get the value of dataObject if the type of dataObject is dataType. In this case you can use your variable "obj" inside scope "if". Try following code:

      private void Sub1<dataType>(Object dataObject)
      {
        if (dataObject is dataType obj)
        {
          var result = obj;
          Console.WriteLine(result.ToString());
        }
      }
    
    0 comments No comments