C
C#2y ago
lunakitty

❔ How to use a variable across an entire class

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/0
BlazeBin - byljqcyiagkv
A tool for sharing your source code with the world!
6 Replies
Denis
Denis2y ago
Class fields are what you want
public class MastodonMonkePostView : ComputerView
{
private MastodonClient _client;

private void Awake()
{
...
_client = new MastodonClient(instance.Value, accessToken.Value);
}

...
}
public class MastodonMonkePostView : ComputerView
{
private MastodonClient _client;

private void Awake()
{
...
_client = new MastodonClient(instance.Value, accessToken.Value);
}

...
}
class fields are: - private - usually prefixed with _ or m_ So, if you'd also want the authClient to be a field, then write it as: private AuthenticationClient _authClient You have to specify the type of the field, var cannot be used. 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
}
}
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
}
}
However, it is strongly advised to avoid public fields, as you allow other classes to change something in your class without you knowing it. 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 (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
Denis
Denis2y ago
Properties in C#
Learn about C# properties, which include features for validation, computed values, lazy evaluation, and property changed notifications.
Denis
Denis2y ago
Fields - C# Programming Guide
A field in C# is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
Denis
Denis2y ago
Remember, reading documentation is an essential skill for any developer blobthumbsup (you really don't want to be dependent on StackOverflow Smadge ....)
lunakitty
lunakittyOP2y ago
Yup the Mastonet authentication docs were actually pretty intuitive once I looked at it
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server