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.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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
}
}
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.
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
}
}
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());
}
}