Declaring a new instance of class with or without parentheses
Both will call the default parameter-less constructor. So I believe both are same.
How to create a new object instance of class being the same type of another instance by only knowing it as base class type?
Downcasting is not possible in C#.
A base object is less than a child object, so you cannot create a base object and cast it to a child.
A base class is missing from the properties and methods added in childs, so you cannot create a base object and convert it to be a child object.
A sofa can be a chair to sit on it, but a chair can not be a sofa to lie down.
But upcasting is OOP fundamental: we can say that child is type of base.
Here you don't want to up or down cast, but create a new instance as formulated in the suggested new title for the question.
So to create another instance of the real base
object type and not a base
you can use reflexion and Activator class.
Example to improve in first intention the code provided
public class Base
{
public string Name;
}
public class Child : Base
{
}
void Go()
{
var a = new Child { Name = "My Name is A" }; // Legal upcast: Child is type of Base
var b = (Child)Test(a);
b.Name = "Sucess";
Console.WriteLine(a.Name);
Console.WriteLine(b.Name);
}
Base Test(Base instance)
{
return (Base)Activator.CreateInstance(instance.GetType());
}
But we can't write:
Base c = new Base();
Child d = (Child)c; // Illegal downcast: Base is not type of Child
Output
My Name is A
Sucess
The use of a generic will be strongly typed and adapted to solve the problem as exposed
void Go()
{
var a = new Child { Name = "My Name is A" };
var b = Test(a);
Console.WriteLine(a.Name);
Console.WriteLine(b.Name);
}
T Test<T>(T instance) where T : Base
{
var instanceNew = Activator.CreateInstance<T>();
instanceNew.Name = "Sucess";
return instanceNew;
}
Because using classes, it can be simplified:
T Test<T>(T instance) where T : Base, new()
{
var instanceNew = new T();
instanceNew.Name = "Sucess";
return instanceNew;
}
But be carefull that this generic solution does not work when passing an object as an ancestor class:
var b = Test((Base)a);
Will be processed as Base
and not Child
.
So we can mix non-generic solution with generic behavior to write:
T Test<T>(T instance) where T : Base, new()
{
var instanceNew = (T)Activator.CreateInstance(instance.GetType());
instanceNew.Name = "Sucess";
return instanceNew;
}
Thus that works better now and it is more consistent:
Base a = new Child { Name = "My Name is A" };
Child b = (Child)Test(a);
Console.WriteLine(a.Name);
Console.WriteLine(b.Name);
Output
My Name is A
Sucess
Possible simplification
Unless you want to do a particular processing in the Test
method, on the real type of the parameter, for a new instance by only knowing this parameter as a type of Base
, to be able to pass any child, and then return it, to refactor some things for example, you can direclty write:
var a = new Child { Name = "My Name is A" };
var b = (Child)Activator.CreateInstance(a.GetType());
b.Name = "Success";
Note: please, don't use base
as a variable name because it is a reserved language keyword, so it does not compile - also, it is an opinion, avoid the use of @base
because it is not clean, and in fact it can be source of problems and confusions.
C# Creating new instance of class from another form
In Form2 class,
First include namespace where the Person
class is present
Then using new
keyword you can create instance of person class
Person personObj = new Person();
If you want to assign values to the properties present in Person class, then
Person personObj = new Person()
{
Name = "Nail",
Age = 23
};
How to create an instance of C# class with a property whose setter is private..from F#
For the given example there is no easy (non-reflection, see below) way, i.e. private setters are inaccessible from C# and F#:
new LoginRequest { Scope = "s" }; // CS0272 The property or indexer 'LoginRequest.Scope' cannot be used in this context because the set accessor is inaccessible
LoginRequest(Scope = "s") // error FS0495: The object constructor 'LoginRequest' has no argument or settable return property 'Scope'.
For accessing the private setter, you could use
let r = LoginRequest()
typeof<LoginRequest>.GetProperty("Scope").GetSetMethod(true).Invoke(r, [| "scope" |])
r.Scope // scope
However, I would strongly discourage the use of reflection. The most obvious reason being that you lose compile time safety.
Create an instance of a class from a string
Take a look at the Activator.CreateInstance method.
C# how to create an instance of a class in one function and then use that same instance in another function
You should create the instance globally for both Game and MockFiler , It will be outside of both functions,
//Creating instance and passing
MockFiler Mock = new MockFiler("###\n# #\n#@#\n###");
//Creating instance for Game
Game game = new Game(Mock);
//Now these can be accessed anywhere within the methods
public void Go()
{
game.Load("h:\theFileNameDoesNotMatterAsItReturnsAString");
string Level = game.Level;
View.ShowGame(Level);
}
public void PassMove(Direction Direction)
{
game.Move(Direction);
string Level = game.Level;
View.ShowGame(Level);
}
Related Topics
Linq Where Ignore Accentuation and Case
Specifying Generic Collection Type Param at Runtime
ASP.NET Core Long Running/Background Task
Ado.Net Closing Connection When Using "Using" Statement
Any Reason to Use Auto-Implemented Properties Over Manual Implemented Properties
How to Get All Subsets of an Array
How to Add 'Comments' to a Jpeg File Using C#
Windows 10 Scrollintoview() Is Not Scrolling to the Items in the Middle of a Listview
The Process Cannot Access the File Because It Is Being Used by Another Process
Add Two Lists of Different Length in C#
System.Web.Httpcontext.Current.User.Identity.Name VS System.Environment.Username in ASP.NET
C# Sortable Collection Which Allows Duplicate Keys
Conversion from List<T> to Array T[]
Await Operator Can Only Be Used Within an Async Method
Elevating Privileges Doesn't Work with Useshellexecute=False
How to Ignore the Utf-8 Byte Order Marker in String Comparisons