C# question about GetType of class - c#

I have an assembly asdf.dll and it has a class 'Class1'.
How can I get the type of Class1?
string a = "Class1"; //Class1 is the name of class in asdf.dll
string typeString = typeof(Class1).FullName; // here I only have the string Class1 and not Class Class1
AssemblyName assemblyName = AssemblyName.GetAssemblyName("asdf.dll");
Type type = Type.GetType(typeString + ", " + assemblyName);
How can I get the type of a class from a string holding the class name?

Type t = Type.GetType("MyDll.MyClass,Mydll")
where MyDll.MyClass is the class Location of your desire class/Form. Mydll is the your dll name. which u want to Call.

typeof(Class1).FullName is already the fully qualified name.
Try just passing that, or using the Type.Name property instead.

Related

Get full name of parameter (namespace, class, method and name) c#

How would I get the namespace, class, method and name of a parameter or variable. For example:
namespace TheNamespace
{
class Theclass
{
void Thing()
{
string thevariable = "";
string b = thevariable.GetFullName();
// b would be equal to TheNamespace.Theclass.Thing.thevariable
}
}
}
How would I do this
Parameters and variables don't have namespace/class name so to get string you are looking for you simply combine Can you use reflection to find the name of the currently executing method? and get name of a variable or parameter:
string b =
System.Reflection.MethodBase.GetCurrentMethod().Name + "." +
nameof(thevariable);

Creating dynamic class from a string containing the class definition

I have a stored procedure which accepts the table name, then it reads the table structure and returns me the table structure in the form of a class definition in a string.
E.g.:
string myString =
"
public class TableName
{
public int Column1 { get; set; }
}
"
Is it possible a create a Class/Type from the string containing the class definition ?
For eg:-
Type type = GenerateType(myString);
I have to pass this type variable to my further piece of code so please help me to create class/type from the string containing the class definition.
You can use the CSharpCodeProvider to compile your result at runtime and then use the Activator - Class to create an object from your generated code.
// compile your piece of code to dll file
Microsoft.CSharp.CSharpCodeProvider cSharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters compilerParameters = new System.CodeDom.Compiler.CompilerParameters();
compilerParameters.GenerateInMemory = true;
compilerParameters.GenerateExecutable = false;
System.CodeDom.Compiler.CompilerResults cResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, "using System; namespace Tables { 'put here your class definition' }");
// then load your dll file, get type and object from class
Assembly assembly = cResult.CompiledAssembly;
Type myTableType = assembly.GetType("Tables.Tablename");
var finalResult = Activator.CreateInstance(myTableType);

Accessing values from the string name of a class at runtime

In my source code for a C# class, I want to use the values of parameters defined within some other class. I want to do it without "hardwiring" the other class name into the source code (e.g., without writing something like "class2.variable").
Rather, I want to pass the name of that other class as a character string at runtime.
I am using C# within Unity. So I want to set the name of the other class as a public string within the Inspector of Unity.
For example, consider these two separate scripts:
using UnityEngine ;
public class ScriptA : ScriptableObject {public static int fred = 5 ; }
and
using System;
using System.Reflection;
using UnityEngine;
public class ScriptB : MonoBehaviour {
object item;
private static string instance;
void Start() {
instance = "ScriptA";
item = ScriptableObject.CreateInstance(Type.GetType(instance));
Type myType = item.GetType();
foreach (FieldInfo info in myType.GetFields())
{
string infoName = info.Name; //gets the name of the field
Debug.Log (" info = " + infoName);
}
}
}
ScriptB works OK ; it accesses ScriptA just from the string "instance", as evidenced by the fact that
the name "fred" to appears in the console.
But how do I access the value of "fred" ; how do I make the number "5" appear on the console?
I have been trying for two days. I have searched extensively for an answer.
Can somebody please help?
FieldInfo has a GetValue method :
public abstract object GetValue(
object obj
)
Try:
Type myType = item.GetType();
foreach (FieldInfo info in myType.GetFields())
{
string infoName = info.Name; //gets the name of the property
Console.WriteLine(" Field Name = " + infoName +"and value = "+ info.GetValue(null));
}

Get all the properties in a class by using Reflection in C#

I have a static class as following:
public static class Person
{
public const string name = "james";
public const string address = "address";
}
Now i want to get the class fields (name and address) from the other class by using Reflection to find the class name and get all its fields.
I tried :
var allTypes = (from assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("TestReflection.Info"))
from type in assembly.GetTypes()
select type).ToArray();
first to get the class then to access to the class and find the class name and its properties but it always returns null when I tried to find a class file in the directory Info.
Could you suggest me the ideas of how can I get all the fields by using Reflection in C#? Thanks

How to extract an object name

i've got a class filled with lists of subclasses:
public class ClassOfKb
{
public List<Data> KbDatas {get;set;}
public List<Product> KbProducts {get;set}
}
public class Data
{
public Guid ID {get;set;}
public byte[] data {get;set;}
public string Name {get;set;}
}
public class Product
{
public Guid ID {get;set;}
public string Name {get;set;}
public byte[] Image {get;set;}
}
i create an object:
ClassOfKb kb = new ClassOfKb
now i'd like to extract the string "Datas" from the sub-object kb.KbDatas, I tried:
string name = kb.KbDatas.GetType().BaseType.Name.Substring(2);
aswell as:
string name = kb.KbDatas.GetType().Name.Substring(2);
but nothing gave me what I need, is there any way to do this?
EDIT: to specify my question, the string I need is the name of the list, except the first two letters! KbDatas => Datas
EDIT2: i did a mistake, the list-names and class-names are different and i need the list-name
You can use Type.GetGenericArguments to solve this
ClassOfKb kb=new ClassOfKb();
kb.KbData = new List<Data>();
string nameOfData = Type.GetType(kb.KbData.ToString()).GetGenericArguments().Single().Name;
OUTPUT : nameOfData = Data
kb.KbProduct = new List<Product>();
string nameOfProduct = Type.GetType(kb.KbProduct.ToString()).GetGenericArguments().Single().Name;
OUTPUT : nameOfProduct = Product
Since that's a collection it is likely that there are multiple Data objects in it, each with a name. You can use String.Join to concat them with a separator:
string names = string.Join(",", kb.KbData.Select(d => d.Name));
If there's just one object you don't get a comma at the end. If there's no object you get an empty string.
erm, since you have a List of Data there will be a sequence of Names.
IEnumerable<string> names = kb.KbData.Select(d => d.Name);
maybe you want just the first one?
string firstName = kb.KbData.First(d => d.Name);
Try this one
string name = kb.KbData[0].Name.Substring(2);
From the sounds of what you've written, you're looking to get the name of the type in the List instance KbData?
If so, I think this may be what you're looking for: https://stackoverflow.com/a/1043778/775479
If you are trying to get the name of the property. There are several methods for doing so.
Get the name of the generic argument from the property itself - If you know the name of the property.
ClassOfKb kb = new ClassOfKb()
{ KbData = new List<Data>(), KbProduct = new List<Product>() };
Console.WriteLine(kb.KbData.GetType().GetGenericArguments()[0].Name);
Get the name of the property from reflection, if you know the data type of the property.
System.Reflection.PropertyInfo pi = kb.GetType()
.GetProperties()
.FirstOrDefault(p=>p.PropertyType == typeof(List<Data>));
Console.WriteLine(pi.Name.Substring(2)); // ignoring the kb prefix
You can achieve this with reflection. This is example without any checks - just show the mechanism:
PropertyInfo propertyInfo = typeof(ClassOfKb).GetProperty("KbData");
Type propertyType = propertyInfo.PropertyType;
Type genericArgument = propertyType.GenericTypeArguments[0];
string name = genericArgument.Name;
Because property KbData is generic List<Data> you need ask for generic arguments of property type: propertyType.GenericTypeArguments[0] and you should test if the type is really generic by genericArgument.IsGenericType and check generic arguments count
If you need the property name than you can use Expression.
The code below define function for extract name prom a property:
public string GetPropertyName<T>(Expression<Func<T>> property)
{
return ((MemberExpression)property.Body).Member.Name;
}
This converts property to property name string:
GetPropertyName(()=>k.KbDatas).Substring(2)

Categories