C
Join ServerC#
help
❔ How to use a variable across an entire class
WWowItsKaylie3/1/2023
I'm wanting to use the
client
var (at the end of Awake) in the Enter key case, so I can post a status when I press enter without redefining the variables every keypress. https://paste.mod.gg/byljqcyiagkv/0DDeno3/1/2023
Class fields are what you want
DDeno3/1/2023
public class MastodonMonkePostView : ComputerView
{
private MastodonClient _client;
private void Awake()
{
...
_client = new MastodonClient(instance.Value, accessToken.Value);
}
...
}
DDeno3/1/2023
class fields are:
- private
- usually prefixed with
- private
- usually prefixed with
_
or m_
DDeno3/1/2023
So, if you'd also want the
authClient
to be a field, then write it as: private AuthenticationClient _authClient
DDeno3/1/2023
You have to specify the type of the field,
var
cannot be used.DDeno3/1/2023
class fields can be public:
public class MyClass
{
public string MyNamePUBLIC;
private string _myNamePRIVATE;
}
public class OtherClass
{
public void Test()
{
var instance = new MyClass();
instance.MyNamePUBLIC = "Some Name"; // OK
instance._myNamePRIVATE = "Other name"; // Compile error
}
}
DDeno3/1/2023
However, it is strongly advised to avoid public fields, as you allow other classes to change something in your class without you knowing it.
DDeno3/1/2023
That is where properties come in. It is a wonderful feature of C#, which allows you to:
- see who references a given property
- control who can read the property (
- control who can write to the property (
- run extra logic before the value of a property is read or written to, e.g., log, filter and validate values, execute more complex logic
- see who references a given property
- control who can read the property (
get
its value)- control who can write to the property (
set
its value)- run extra logic before the value of a property is read or written to, e.g., log, filter and validate values, execute more complex logic
DDeno3/1/2023
Learn more here: https://learn.microsoft.com/en-us/dotnet/csharp/properties
DDeno3/1/2023
And here is the official documentation of C# fields: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/fields
DDeno3/1/2023
Remember, reading documentation is an essential skill for any developer
(you really don't want to be dependent on StackOverflow
....)


WWowItsKaylie3/1/2023
Yup the Mastonet authentication docs were actually pretty intuitive once I looked at it
AAccord3/2/2023
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.