initializing variables in c# - c#

I'm a bit confused.
I have the following code:
public class MyClass
{
public string DoSomething(string TheString)
{
int TheID;
string TheString = "";
}
}
This works fine; it compiles. However, why doesn't this work?
public class MyClass
{
public string DoSomething(string TheString)
{
private int TheID {get;set;}
private string TheString {get;set;}
}
}
I want to make these variables private. What do I need to change?

Private variables are only valid at the class level:
public class MyClass {
private int TheID {get;set;}
private string TheString {get;set;}
public string DoSomething(string TheString) {
}
}
Variables defined inside a method are local in scope and they only exist inside that method. Nothing outside the method can access them. It makes no sense to declare a local variable as private.

They are scoped inside the method - you can't access them outside of it. You can think of them as being private.

Related

c# how assign static class to instance variable?

Static members can't be called with instance, like instance.myStaticProperty.
Is there any way, that I can have an instance variable that will be an alias of static self class? like:
class myClass
{
public string a ="hello";
public static string b ="world";
public myClass myVariable = global::myClass; // <--- phseudo code
}
and i could call:
myClass instance= new myClass();
instance.myVariable.b; //
No, there is not. The closest you get is using a using.
Your static class definition:
class ClassA
{
public static string A = "A";
}
And to use it:
using StaticClassA = ConsoleApp1.ClassA;
class Program
{
static void Main(string[] args)
{
string a = StaticClassA.A;
}
}
Not too much to gain though, but it might ease your naming a little.
Another (somewhat cooler) option is a static using:
using static ConsoleApp1.StaticClassA;
class Program
{
static void Main(string[] args)
{
string a = A;
}
}
You're attempting to do an anti-pattern there.
Static properties are properties not defined in an instance (object) of that class, but by the class itself. And as such, you can access and modify them whenever you choose to, provided you have the required scopes to do so.
I don't see the problem in calling MyClass.StaticProperty = <some expression>, if indeed the functions the static property do, are static. If it's something part of the object, something you don't connect with the class itself, i.e it might be different for each instanced object of that class, then just turn it into a regular property instead.
Example of some static properties and methods:
public class DoMath
{
public static string Pi { get; private set; } = "3.14";
public static double X {get; set;}
public static double Y {get; set;}
public static double Sum() => X + Y;
}
DoMath.X = 3.5;
DoMath.Y = 4;
double result = DoMath.Sum();
Console.WriteLine($"Pi is equal to {DoMath.Pi}.");
If you truly wish something to be static, then don't try to make it non-static. Simply declare it as such.
Static members are shared across all instances of the class or all instances of Class Of T of same T.
So you can access static properties outside of class by using the ClassName.VarName or directly by the VarName from within the class.
You can access static fields and properties and methods from all non static methods.
You can also add an instance member mapping a static member.
Instances of a static thing can't exist in addition to the static existence itself.
So you can write this:
class myClass
{
public string a = "hello";
static public string b = "world";
public string B { get { return b; } set { b = value; } }
public void DoSomething()
{
b = "new world";
}
}
And use it like that:
myClass instance= new myClass();
instance.DoSomething();
myClass.b = "another world";
instance.B = "C# world";

Set field via class

For example if we have class MyClass with private field. Is it possible to set value via class object.
public class MyClass { private int field; }
public class Program
{
public static void Main()
{
MyClass cl = new MyClass();
cl = 10; // set value
}
}
It's not directly possible like that in C#, but it's possible to do it through implicit operator overloading by instantiating the class from a value.
public class MyClass
{
private int field;
public static implicit operator MyClass(int value)
{
return new MyClass { field = value };
}
}
Which you can then use like:
MyClass myClass = 100;
That's the closest you will get to what you want.
Other than that you can really only do it through constructors or reflection.
No. But you can expose a method that set the value.
private int _field;
public void SetMyPrivateField(int val)
{
_field = val;
}
or you can take pass the value in with the constructor
public class MyClass
{
private int _field;
public MyClass(int val)
{
_field = val;
}
}
Is it possible to set value via class object.
It is indeed possible to do this using reflection:
public class Program
{
public static void Main()
{
MyClass cl = new MyClass();
var fi = cl.GetType().GetField("field", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
fi.SetValue(cl, 10);
Console.WriteLine(fi.GetValue(cl));
}
}
But there is probably a reason for the field being private so you shouldn't do this. But you can.
This violate Object Oriented concepts which used in C#
so, you shouldn't do that and save encapsulation concept
by using
Property
public Get{get=>field;set=>field=value;}
Setter & Getter
Constructor
public MyClass(int field) {this.field = field;}
It really depends on how much encapsulation you want to use. Realistically the best way to think about this is to go for the way that limits the accessibility of the variable as much as possible.
You want a variable/property to be read/write outside of the class
Use a public property. This gives you read and write access. There is no need for a backing variable as it's all readable/writeable anyway.
public MyClass
{
public int Field {get; set;}
}
You want a variable/property to be readable outside of the class, but not writeable
There is a couple of ways to skin a cat here. One way is to still use a property but make the setter private, meaning it can only be set inside the class.
public MyClass
{
public int Field {get; private set;}
public MyClass(int field)
{
Field = field;
}
}
I prefer to have a backing readonly variable if it's only to be set inside the constructor and it will never change.
public MyClass
{
private readonly int _field;
public int Field {get=>_field;}
public MyClass(int field)
{
_field = field;
}
}
You want a variable to be passed into a class but not readable/writeable from that point
You should just use a private readonly variable.
public MyClass
{
private readonly int _field;
public MyClass(int field)
{
_field = field;
}
}

C# private variable & java private variable getter & setter - Difference?

I am trying to understand the difference between the C# auto declaration of variables with getters & setters & the java declaration.
In java I usually do this:
private int test;
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
But in C# I tried something like this:
private int test { public get; public set};
But that did not allow access to the variable at all.
So I ended up with this:
public int test { get; set; }
So this way I could access the variable test from outside of the class.
My question is, what is the difference between these two? And is the C# implementation of making the variable public a bad idea?
In C# I have declared the variable as "public". Whereas in java it is declared as "private". Does this have any impact?
Found a really good answer (in addition to those below) here
It is exactly the same.
The automatic property you defined in C# will compile down to getter and setter methods anyway. They are classified as "syntactic sugar".
This:
public int Test { get; set; }
..is compiled to this:
private int <>k____BackingFieldWithRandomName;
public int get_Test() {
return <>k____BackingFieldWithRandomName;
}
public void set_Test(int value) {
<>k____BackingFieldWithRandomName = value;
}
In the first example you have a backing field.
In C# You can do:
private int test { get; set; };
Or make the property public (Perfectly valid)
public int test { get; set; };
You can also have backing fields in C#, these were more common before Properties were introduced in the language.
For instance:
private int _number = 0;
public int test
{
get { return _number; }
set { _number = value; }
}
In the above example, test is a public Property that accesses a private field.
Here is the solution, which is provided by the C# compiler to eaisly create getter and setter method.
private int test;
public int Test{
public get{
return this.test;
}
public set{
this.test = value;
}
}

C# Cannot Reach Class Elements

It seems like a very simple error, but I could not solve it.
I have created a Class named User in User.cs, and when I instantiate it in another .cs file, it does it, but I cannot either change its properties or reach its properties.
User user = new User();
I create a new instance like this, but then I cannot reach. For example:
user.name
The content of User class is the following:
public class User
{
public static string name;
public static int age;
public static int height;
public static int weight;
}
What is the reason and how can I solve it?
Thanks
You have created a static object, don't instantiate the class to use it, just do
User.name
Alternativly remove the static keyword.
The word static means you don't need to make a new insance of the class to access something so for a class with
public Class {
public static object myAttribute;
}
Class.myAttribute
But if you don't use the static key word
public Class {
public object myAttribute;
}
Class myClass = new Class();
myClass.myAttribute;
You want to use a static value when your value does not depend on any other variables in the same class. When they do depend on varibles (or manipulations of variables) in the same class then use non static.
remove keyword static from fields
Is name public member? Set it public or create a public property to access it...
public string Name { get { return name; } }
EDIT: as name is a static member, you cannot write myUser.name. It's User.name. I think you should remove static (and learn some basis...).
What is the error message that occurs during build? It should be clear enough.
You have to declare name as public in the user class. For example:
public string name { get; set; }
You cannot access static fields from the instance of a class. You can either not declare the fields static:
public class User
{
public string name;
public int age;
public int height;
public int weight;
...
Or you can access the class statically:
User.name

force variables from superclass to be assigned (at compile time)

I have a superclass which has a bunch of variables.
e.g.
string s1= ""; string s2= ""; string s3= "";
...etc
I'd like to guarantee that these variables get overridden (assigned something useful) in the subclass that inherits from this superclass, at compile time.
is there an elegent way of doing this?
Make all the constructors in the base class take them as parameters, and set them from those constructors:
protected BaseClass(string s1, string s2, string s3)
{
this.s1 = s1;
this.s2 = s2;
this.s3 = s3;
}
...
// Just for example
public DerivedClass(string x) : base("foo", "bar", x)
{
}
Hopefully they're private fields anyway, so the derived class couldn't set them directly anyway, right? :)
You cannot have virtual fields in C#. If you really need this, you could use Properties which you then override and give a default value in your subclass.
public class A
{
private string s1;
public virtual string S1
{
get { return this.s1; }
}
}
public class B : A
{
private string myString = "default";
public override string S1
{
get
{
return this.myString;
}
}
}

Categories

Resources