How to use class name as parameter in C#
Object createObjectBy(Type clazz){
// .. do construction work here
Object theObject = Activator.CreateInstance(clazz);
return theObject;
}
Usage:
createObjectBy(typeof(A));
Or you could simply use Activator.CreateInstance
directly :-)
How to pass a Class as parameter for a method?
The function you're trying to implement already exists (a bit different)
Look at the Activator class: http://msdn.microsoft.com/en-us/library/system.activator.aspx
example:
private static object CreateByTypeName(string typeName)
{
// scan for the class type
var type = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.Name == typeName // you could use the t.FullName as well
select t).FirstOrDefault();
if (type == null)
throw new InvalidOperationException("Type not found");
return Activator.CreateInstance(type);
}
Usage:
var myClassInstance = CreateByTypeName("MyClass");
pass class type as parameter c# and used with dictionary
Using Generics
Your current approach will give you much trouble. As you are going to pass a Type object for your class, you will need reflection to be able to create the Dictionary
.
As an alternative, I propose to you to create a generic method:
public Dictionary<object, object> GetDetails<TClass>()
{
MvcDemoDBEntities db = new MvcDemoDBEntities();
Dictionary<TClass, object> dict = new Dictionary<TClass, object>();
var data = (from h in db.People
select h).ToList();
foreach (var item in data)
{
dict.Add(data, true);
}
return dict;
}
Use it like this:
List<people> list = GetDetails<people>().Keys.ToList();
Using Type
Of course, this can be done using a Type object, this requiers the use of reflection to be able to create an object of which type we don't know (that object is the dictionary). This is done as follows:
public Dictionary<object, object> GetDetails(Type Class)
{
//Null check
if (null == Class)
{
throw new ArgumentNullException("Class");
}
MvcDemoDBEntities db = new MvcDemoDBEntities();
//Get the generic dictionary type:
Type DictType = typeof(Dictionary<,>).MakeGenericType(Class, typeof(object));
//Create the dictionary object:
object dict = Activator.CreateInstance(typeof(DictType));
//Get the Add method:
var add = DictType.GetMethod("Add", new Type[]{Class, typeof(object)});
var data = (from h in db.People
select h).ToList();
foreach (var item in data)
{
//add to the dictionary:
add.Invoke(dict, new object[]{item, true});
}
return dict;
}
Use like this:
List<people> list = GetDetails(typeof(people)).Keys.ToList();
Digging deeper
I notice you have this line:
var data = (from h in db.People select h).ToList();
You may be interested in changing People
to a property matching the name of the class you pass in. This can only be archived via reflection. In a similar way as how we got the Add
method of the dictionary, we can get a property from the object db
which name is given by the argument type.
I'll present this as a second method to be called by the first.
Using Generics
public IEnumerable<TClass> GetCollection<TClass>(MvcDemoDBEntities db)
{
//get the type of db
var dbType = db.GetType();
//get the name of the type TClass
var name = typeof(TClass).Name;
//get the property
var prop = dbType.GetProperty(name);
//read the property and return
return prop.GetValue(db);
}
To use, replace this:
var data = (from h in db.People select h).ToList();
With this:
var data = (from h in GetCollection<TClass>(db) select h).ToList();
Using Type
Here the struggle is that we don't know the item type... so I'll use IEnumerable.
public IEnumerable GetCollection(MvcDemoDBEntities db, Type Class)
{
//get the type of db
var dbType = db.GetType();
//get the name of the type Class
var name = Class.Name;
//get the property
var prop = dbType.GetProperty(name);
//read the property and return
return prop.GetValue(db);
}
To use, replace this:
var data = (from h in db.People select h).ToList();
With this:
var data = (from h in GetCollection(db, Class).Cast<object>() select h).ToList();
Using class name as method parameter and return type
The key word in your question is generic
, so yes you can do this by utilising C# generics. For example:
public static T Deserialize<T>(this XDocument xdoc)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(xdoc.ToString()))
{
T cfg = (T) serializer.Deserialize(reader);
return cfg;
}
}
And now you call it like this:
CarConfiguration x = xmlDocument.Deserialize<CarConfiguration>();
Related Topics
Why Does the Linq Cast<> Helper Not Work with the Implicit Cast Operator
Troubleshooting "Program Does Not Contain a Static 'Main' Method" When It Clearly Does...
Binding Selecteditems of Listview to Viewmodel
How to Split an Ienumerable<String> into Groups of Ienumerable<String>
C# Getting Value of Params Using Reflection
C# Image.Clone Out of Memory Exception
How to Change Listbox Selection Background Color
How to Pass a Table-Value Parameter
Dynamically Changing Schema in Entity Framework Core
How to Test Smtpclient Before Calling Client.Send()
How to Define Multiple Names for Xmlelement Field
How to Check for Nulls in a Deep Lambda Expression
Xmlserializer Serialize Generic List of Interface
Datagridview Changing Cell Background Color