This question already has answers here:
C# Reflection: How to get class reference from string?
(6 answers)
Closed 8 years ago.
I am new to C# and writing some automation framework .I want to initialize a class dynamically based on condition .
i get the name of the class as a string based on conditions .
Ex : "Vehicle_"+ typeOfvehicle => Which will on run time may be Vehicle_2Wheeler or Vehicle_3Wheeler or Vehicle_4Wheeler .
I am using if , else statement for now . But if i can initialize the class with the type of Class i want to dynamically it would be better .
I think i need to use the Reflection API but not sure how to achieve this .
Please let me know if some one has an idea of this .
In C# Type.GetType("Truck") will return a Type that you can then instantiate
var type = Type.GetType("MyProject.Truck");
var instance = (Vehicle)Activator.CreateInstance(type);
Though if you don't know the specific type at compile time, leave off the cast, and just use object, dynamic, or a base class.
To pass args:
Activator.CreateInstance(type, arg1, arg2);
Related
This question already has an answer here:
What does (datatype, datatype) x = (value, value) mean in C#? What is the actual data type of x?
(1 answer)
Closed 1 year ago.
i am still learning c# and .net core. Some time ago one guy send to me a exercise on which unfortunately i fall off mainly because of this function definition :
public static (int UserId, decimal MaximumTotalInstallment)[] Process(User[] users) {}
This is a library function which is used in XUnit test class in another namespace :
var expected = new[] {(1, 100m), (2, 1000m)};
// when
var output = BatchProcessingLibraryClass.Process(input);
// then
output.Should().BeEquivalentTo(expected);
Could You please tell me what this call of lib function exactly do ? I dont meet this kind of function declaration before.
You cannot tell what it does from the name (other than "process"), but you can tell what inputs are expected and what outputs are produced
Inputs - An array of User type called users.
Output - An array of a tuple. This tuple has two fields an integer named UserId and a decimal named MaximumTotalInstallment. This type is equivalent to ValueTuple<int,decimal>.
Other notes, the method is static which means it is called not for a particular instance of a class, but callable (like a library) from anywhere else.
This question already has answers here:
C# Is it possible to pass a type into a method and have the method return an object of that type?
(7 answers)
Closed 2 years ago.
Ok, so this kinda goes over my head a little. also, I don't even know if it is possible to do so
I really don't even know the terms for a lot of this
First off this is for space engineers a game I play that has open c# script to interact with the game and I have found it very fun and a great way to learn some basics of code
Now what I'm trying to do is make a method, I think that is what it is called its this "internal List<> GetBlocksWithName", and what this method would do is search all blocks on a ship and then convert it to the right type then return a list of that type
but my issue is that I want to pass the 'type' I want to convert to at the end. not only if I try to call the method does it tell me that it's not valid. when I try to use the type that is passed through in the method as a type it says it's not a type
also, I'm not sure how to send the list back if its a different type each time
here is the code I'm using
internal void BlockScan()
{
GetBlocksWithName(IMyMotorAdvancedStator, "SolarHing"); // <- compile error IMyMotorAdvancedStator ('IMyMotorAdvancedStator' is a type, witch is not vaild in the give context)
return;
}
internal List<> GetBlocksWithName(Type blockType,string nameOfBlocks) // <- compile error List<>(Unexpected use of an unbound generic name) its because of an unfinshed return not sure how to specife the type if it will be different every time
{
List<IMyTerminalBlock> temp = new List<IMyTerminalBlock>();
GridTerminalSystem.SearchBlocksOfName(nameOfBlocks, temp);
return temp.ConvertAll(x => (blockType)x); // <- compile error blockType ('blockType' is a varible but is used like a type)
}
I know that there is a lot of stuff in there that is very specific to space engineers script but if someone could help me out would be of great help thanks in advance
Try the following
internal void BlockScan()
{
GetBlocksWithName<IMyMotorAdvancedStator>("SolarHing");
return;
}
internal List<T> GetBlocksWithName<T>(string nameOfBlocks)
{
List<IMyTerminalBlock> temp = new List<IMyTerminalBlock>();
GridTerminalSystem.SearchBlocksOfName(nameOfBlocks, temp);
return temp.ConvertAll(x => (T)x);
}
You pass in the Type = T as a generic, and use the Generic T to convert your variable x to the correct type.
Have a look at Generic programming in the documentation. To get a better understanding.
This question already has answers here:
Is there a way to abbreviate a custom class type declaration?
(4 answers)
Implicit typing; why just local variables?
(6 answers)
Closed 2 years ago.
Why do I have to write:
public VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName> field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();
Instead of:
public var field = new VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>();
Is there any way to shorten this ridiculous declaration?
Why do I have to write two identical types in a single line?
Upd.
I have found that using "dynamic" keyword instead of "var" perfectly solves this problem!
Please feel free to provide any info on the perfomance (or other) issues with this solution!
You can use a type alias. Documentation can be found here. Link to alias for generic class: here
using YourShortName = VeryLongClassNameThatHurtsMyEyes<AnotherVeryLongClassName>;
Usage
public YourShortName field = new YourShortName();
See here for why you can only use var for local variables.
And see here for an in depth look at dynamic and why it's not even remotely close to using var.
This question already has answers here:
Casting a variable using a Type variable
(11 answers)
Closed 4 years ago.
I have a Type variable and I need to cast another object to it. (one which I know what the type is, but currently its an "object" type). I need to do this for reasons that aren't really important to the answer.
// Pseudocode
MyObjectClass myTypedVar = new MyObjectClass();
Type myKnownType = myTypedVar.GetType();
var anotherObject = (myKnownType) anObjectVarThatIsReallyMyObjectClass;
I've read this page Type Casting an Object using a "Type" Object in C# and I understand but I don't think it applies directly. I anticipate a solution using reflection, but I just haven't been able to figure it out myself.
If I understand you correctly, you could use the Convert.ChangeType method:
var anotherObject = Convert.ChangeType(anObjectVarThatIsReallyMyObjectClass, myKnownType);
You won't get any kind of compile-time checking when using a dynamic type like this though. Please refer to the following blog post for more information about this.
Generic type parameters and dynamic types in C#: https://blog.magnusmontin.net/2014/10/31/generic-type-parameters-and-dynamic-types-in-csharp/
This question already has answers here:
Pass An Instantiated System.Type as a Type Parameter for a Generic Class
(6 answers)
Closed 8 years ago.
I need to create a generic object based on a type that is stored in a database. How can I acheive this? The code below (which won't compile) explains what I mean:
string typeString = GetTypeFromDatabase(key);
Type objectType = Type.GetType(typeString);
//This won't work, but you get the idea!
MyObject<objectType> myobject = new MyObject<objectType>();
Is it possible to do this kind of thing?
Thanks
Type type = typeof(MyObject<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);
Also - watch out; Type.GetType(string) only checks the executing assembly and a few system assemblies; it doesn't scan everything. If you use an assembly-qualified-name you should be fine - otherwise you may need to get the Assembly first, and use someAssembly.GetType(string).