Hi
i'm still experiment with instantiation and tried this: i moved the instantiation from Main into the constructor (as recommended by Sachin Singh in a previous post). But i get the error "the name 'auto' doesn't exist".
Thanks.
V.
using System;
class Car
{
string model;
public Car()
{
Car auto = new Car();
}
static void Main(string[] args)
{
new Car();
auto.model = "Mustang";
Console.WriteLine(auto.model);
}
}
Aravind GovindarajPosted Jan 3, 2023, 6:30 PM
Please refer these example why we need to instantiate in constructor...
Valerie MeunierPosted Jan 3, 2023, 10:32 PM
Thanks
Valerie MeunierPosted Jan 3, 2023, 5:09 PM
Thanks, but can you fix the error of your own code, please?
I think it is not possible to fix it, because from a static method, you need instantiation in order to reach auto. The only solution would be to add Car auto = new Car(); in Main, but then, why puting it in the constructor?
Aravind GovindarajPosted Jan 3, 2023, 11:32 AM
please follow the link for the Initiation of the constructor
https://www.onlinebuff.com/article_what-is-a-constructor-in-c-and-list-types-of-constructors-in-c_19.html#:~:text=A%20benefit%20of%20using%20a,constructor%20or%20an%20instance%20constructor
Valerie MeunierPosted Jan 3, 2023, 11:14 AM
Well, as i said, i'm experimenting with instantiation and, as suggested by your collegue, it would be better to put the instantiation into the constructor. So that's what i'm trying here. I personnaly indeed would put it in Main in this case.
So my questions are:
1) you gave me a code to perform that but i still get an error. Can you tell me, independently of its' better or not to do like this, how to fix that error?
2) I know the instantiation can be at class level (better in case of the fields are used in several methods) otherwise at method level (e.g. in Main). But what's the benefit to put it into a constructor like this?
Thanks again.
Aravind GovindarajPosted Jan 3, 2023, 9:41 AM
I am not sure why you need to create an instance within the same class. In your case, my assumption is your main method suppose to be in class A and you have to create another class as Car.
eg.,
class program {
static void main (){
// create a car instance here... also if you wana to use it as console app. yes you will get static issue because your main functional is in statsic. you have to sepeate the layer to avoid this issue
}
}
class Car {
}
Valerie MeunierPosted Jan 2, 2023, 7:08 PM
I tried both version and in both cases i get the error:
an object reference is required for non-static fields ...
at line: auto.model in Main.
Aravind GovindarajPosted Jan 2, 2023, 1:39 PM
please follow this