Passing just a type as a parameter in C#
There are two common approaches. First, you can pass System.Type
object GetColumnValue(string columnName, Type type)
{
// Here, you can check specific types, as needed:
if (type == typeof(int)) { // ...
This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));
The other option would be to use generics:
T GetColumnValue<T>(string columnName)
{
// If you need the type, you can use typeof(T)...
This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);
Passing type as a parameter
Use generics:
public (bool,Point) GetItemPosition<T>() where T: IMyBaseType
{
...
}
In the method, you would refer to the passed in type as T
. You can check, for example, if an object obj
is of type T
with is
:
if (obj is T) { ... }
The caller would look like:
GetItemPosition<SomeDataItem>()
How to pass an Object type to Type parameter in C#
The typeof
keyword when you know the class at compile time.
SetValuesToObject(typeof(Product),datarow);
You can also use object.GetType()
on instances that you don't know their type at compile time.
c# passing class type member as parameter works as call by value
From the ref documentation
When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The ref keyword makes the formal parameter an alias for the argument, which must be a variable.
So I'll try to explain the makes the formal parameter an alias as simple as possible.
Without ref
Imagine the stageTerrain
from private MapEntity stageTerrain = new MapEntity();
as a box holding an address.
Imagine the mapEntity
from public void RandomChoice(MapEntity mapEntity)
as another NEW box.
- If you change a property of the mapEntity before assigning a new object, it will also change the value of the calling variable.
When you call the RandomChoice
the mapEntity
is a new box holding the same memory address as the stageTerrain
box.
Now mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];
will assign the selected value only to the New box.
With ref
Imagine the mapEntity
from public void RandomChoice(ref MapEntity mapEntity)
as an alias for an already existing box that will hold the memory reference just with a different name. (thus the alias statement)
When you call the RandomChoice
the mapEntity
is the stageTerrain
box.
C# Is it possible to pass a type into a method and have the method return an object of that type?
In your given example you are probably better served just doing the following:
MyClass val = myObject as MyClass;
However to answer your question - yes, the answer is to use generics:
protected T GetAValue<T>(object someObject)
{
if (someObject is T)
{
return (T)someObject;
}
else
{
// We cannot return null as T may not be nullable
// see http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c
return default(T);
}
}
In this method T is a type parameter. You can use T in your code in exactly the same way that you would any other type (for example a string), however note that in this case we haven't placed any restriction on what T is, and so objects of type T only have the properties and methods of the base object
(GetType()
, ToString()
etc...)
We must obviously declare what T is before we can use it - for example:
MyClass val = GetAValue<MyClass>(myObject);
string strVal = GetAValue<string>(someObject);
For more information take a look at the MSDN documentation on Generics
How to pass any type of object as input parameter with only 1 method
If this service does not need to be interoperable, you can switch to NetDataContractSerializer
, which uses full .NET type information, and is able to serialize many more types (but not any type - that's impossible).
Grab the UseNetDataContractSerializerAttribute
from this answer and apply like so:
[UseNetDataContractSerializer]
public class PdfPrinterService : IPdfPrinter
{
public PdfPrinterResponse Print(PdfPrinterRequest request)
{
return PdfPrinterFacade.PrintPdf(request);
}
}
[MessageContract]
public class PdfPrinterRequest
{
[MessageBodyMember]
public object Document { get; set; }
}
How do I use reflection to call a generic method?
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with MakeGenericMethod:
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
For a static method, pass null
as the first argument to Invoke
. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using dynamic
- if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.
Related Topics
How to Implement a Rule Engine
What Is the Meaning of Thread-Agility in ASP.NET
Generate 16-Bit Grayscale Bitmapdata and Save to File
How to Use Npm with ASP.NET Core
How Can Xml Documentation for Web API Include Documentation from Beyond the Main Project
Manual Editing of *.Designer.Cs File
Finding a Subsequence in Longer Sequence
Caliburn.Micro Serialization Issue When Implementing Propertychangedbase
JSON.Net Serialize Directly from Oledbconnection
How to Group by on 2 Child Entities and Get Total of Both This Child Entities
Dependency Injection Type-Selection
Case Statement Block Level Declaration Space in C#
Regex Split String But Keep Separators
The Name <...> Does Not Exist in the Namespace Clr-Namespace <...>
How Can a C++ Windows Dll Be Merged into a C# Application Exe