C
C#11mo ago
Asela

Just a random question

I'm not trying to solve a problem, rather I am looking for specific words to expand my C# vocabulary. What did I do from line 11 through 15? Is that what you call an instance of an object? Normally, I instantiate objects by doing this: Type name = new Type(); but I'm not entirely sure what you call what I did from line 11 through 15.
No description
6 Replies
Angius
Angius11mo ago
You declared fields Private fields, to be more precise Each and every one of them being, most probably, null Or default
Asela
AselaOP11mo ago
Ahh But they are first initialised in the Start method right?
Angius
Angius11mo ago
Yes, that's where you initialize them
Asela
AselaOP11mo ago
Sweet, thanks
i like chatgpt
i like chatgpt11mo ago
Declaration Without Initialization
class User
{
// (instance) field declaration without initialization
// they are automatically assigned a default value
// 0 for int
// null for string
// false for bool
public int Age;
public string Name;
public bool IsActive;

public void Print()
{
// local variable declaration without initialization
// they are unassigned, you must assign them manually.

int foo;
string bar;
bool baz;
}
}
class User
{
// (instance) field declaration without initialization
// they are automatically assigned a default value
// 0 for int
// null for string
// false for bool
public int Age;
public string Name;
public bool IsActive;

public void Print()
{
// local variable declaration without initialization
// they are unassigned, you must assign them manually.

int foo;
string bar;
bool baz;
}
}
Initialization Order
var user = new User { Age = 30 /* third */ };
Console.WriteLine(user.Age);
// output: 30
// initialization order:
// 1. instance field initializer
// 2. constructor
// 3. object initializer
// for the following example, 20 overwrites 10 and 30 overwrites 20, so the output becomes 30.
class User
{
public int Age = 10; // first

public void Print()
{
Age = 20; // second
}
}
var user = new User { Age = 30 /* third */ };
Console.WriteLine(user.Age);
// output: 30
// initialization order:
// 1. instance field initializer
// 2. constructor
// 3. object initializer
// for the following example, 20 overwrites 10 and 30 overwrites 20, so the output becomes 30.
class User
{
public int Age = 10; // first

public void Print()
{
Age = 20; // second
}
}
The complete order list (when you class inherits from another class, has static field, etc): 1. Static fields 2. Static constructor 3. Instance fields 4. Base static fields 5. Base static constructor 6. Base instance fields 7. Base constructor 8. Constructor 9. Object initializer.
Asela
AselaOP11mo ago
Thanks!
Want results from more Discord servers?
Add your server