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)?