Reputation: 29
I have a simple question. I know that an object of a class must be initialized first to use that (non-static) class in C#.
So (I think) this piece of code does that:
namespace ConsoleApp10
{
class Program
{
public class Person
{
public string Name;
public void Introduce0()
{
Console.WriteLine("My name is " + Name + ".");
}
}
static void Main(string[] args)
{
var person0 = new Person();
person0.Name = "Marry";
person0.Introduce0();
Console.ReadKey();
}
}
}
And the result is:
My name is Marry.
Then I tried to the same thing with a static method:
namespace ConsoleApp10
{
class Program
{
public class Person
{
public string Name;
public void Introduce0()
{
Console.WriteLine("My name is " + Name + ".");
}
public static Person Introduce1(string str0)
{
var temp0 = new Person();
temp0.Name = str0;
temp0.Introduce0();
return temp0;
}
}
static void Main(string[] args)
{
var person0 = Person.Introduce1("Marry");
Console.ReadKey();
}
}
}
And the result is, as expected, the same:
My name is Marry.
And then I added two pieces of code in my Main method:
static void Main(string[] args)
{
var person0 = Person.Introduce1("Marry");
person0.Name = "Sarah";
person0.Introduce0();
Console.ReadKey();
}
And the result is:
My name is Marry.
My name is Sarah.
So, here are my questions:
In the last example, why don't I have to initialize a Person object to access the Name field and Introduce0 method? Is accessing a static method means an auto-initialization? Or Is it because Introduce1 method has a Person object initialization in it (temp0)?
Upvotes: 2
Views: 62
Reputation: 9616
Or Is it because
Introduce1
method has a Person object initialization in it (temp0)?
Yes, exactly. Introduce1
is a static method, which means that you can call it without creating a Person
object first.
Then, in Introduce1
, you create a new Person
object, which can subsequently be used to call instance methods of Person
, like Introduce0
.
Note that your code is functionally equivalent to
static void Main(string[] args)
{
var temp0 = new Person();
temp0.Name = "Marry";
temp0.Introduce0();
var person0 = temp0;
person0.Name = "Sarah";
person0.Introduce0();
Console.ReadKey();
}
Upvotes: 2
Reputation: 9639
It is the second reason: "Is it because Introduce1 method has a Person object initialization in it (temp0)?". You are initializing a Person object, which you return from Person.Introduce1. It is perfectly valid for a method in a class to return an instance of that class.
Upvotes: 0