Calling a double from within a class - c#

Hello,
I'm trying to call the double paying from within the class "Wallet"
but when i try to do this it gives this error:
Member'Mc_DOnalds.Program.Paying' cannot be accessed with an instance reference; qualify it with a type name instead.
This is in the class Wallet.
class Wallet
{
public double WalletCustomer = 100;
Program Betalen = new Program();
public void Pay()
{
WalletCustomer = (WalletCustomer - Betalen.Paying);
}
}
}
This is in the Program.cs
public static double Paying = 0;

Because Paying is static, you don't need to create an instance of the class to access the property. Try this (take a look on how I access the Program.Paying):
class Wallet
{
public double WalletCustomer = 100;
public void Pay()
{
WalletCustomer = (WalletCustomer - Program.Paying);
}
}
}

For static member you need to use class name instead of instance
WalletCustomer = (WalletCustomer - Program.Paying);
You access the members of a static class by using the class name
itself. For example, if you have a static class that is named
UtilityClass that has a public method named MethodA, you call the
method as give below, MSDN.
UtilityClass.MethodA();

This error is coming because you are trying to access your non static member from static class.
Solution: Either mark your member as static or change your Calling function to Non-Static.
or access your Non-Static Member with Class Name
Here is how?
class Wallet
{
public static double WalletCustomer = 100;
Program Betalen = new Program();
public void Pay()
{
WalletCustomer = (WalletCustomer - Betalen.Paying);
}
}
Or
class Wallet
{
public double WalletCustomer = 100;
Program Betalen = new Program();
public void Pay()
{
WalletCustomer = (WalletCustomer - Betalen.Paying);
}
}
In your Main Program
Program.Paying = 0;

According to LeakyCode, in C#, unlike VB.NET and Java, you can't access static members with instance syntax. You should do:
MyClass.MyItem.Property1
To refer to that property or remove the static modifier from Property1 (which is what you probably want to do). For a conceptual idea about what static is, see my other answer.
Poom

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";

How can we call the private class function or methods to some other class in C#?

I have a private static class and I am trying to access AddtwoNum() method from SomePrivateClass to SomePublicClass in C# and It is not allowing me to do so.
class SomeClass
{
private static class SomePrivateClass
{
public static void AddtwoNum(int num1, int num2)
{
//do some stuff here
}
}
class SomePublicClass
{
SomePrivateClass.AddtwoNum(); //Error: The name AddtwoNum does not exist in the current context.
// how to call AddtwoNum() method here???
}
}
You can use Reflection to do that, but I would rather avoid calling private members, as it breaks encapsulation and relies on internal implementation details. This will make your code less stable.
Your code could be something like the following:
Get the type you are interested by using Assembly.GetType
Get the method info you would like to execute by using Type.GetMethod
Call the method on the given object by using MethodInfo.Invoke
The code could look something like this:
[TestMethod]
public void TestMethod1()
{
var type = Assembly.GetExecutingAssembly().GetType("ClassLibrary2.SomeClass");
var nestedType = type.GetNestedType("SomePrivateClass", BindingFlags.NonPublic);
var method = nestedType.GetMethod("AddtwoNum", BindingFlags.Static | BindingFlags.NonPublic);
method.Invoke(null, new object[] { default(int), default(int) });
}
This way, it works for me:
class SomeClass
{
private static class SomePrivateClass
{
public static int AddtwoNum(int num1, int num2)
{
return num1 + num2;
}
}
class SomePublicClass
{
private int x = SomePrivateClass.AddtwoNum(1, 2);
public void InteractWithSomePrivateClass()
{
SomePrivateClass.AddtwoNum(1,2); //no problem
}
}
}
Same namespace, same assembly, private respected.
As stated by Microsoft,
private members are accessible only within the body of the class or
the struct in which they are declared.
So, within the body of the class "SomeClass", the class "SomePrivateClass" is known.
The class "SomePublicClass" is within the body of the class "SomeClass", so it knows the "SomePrivateClass" too.
Note: SomeClass is not really a member, but the definition applies anyway. Here is a more general statement:
private: The type or member can be accessed only by code in the same
class or struct.
I know this is not exactly what you are looking for, but why not mark SomePrivateClass as internal instead of private. Then the class is only visible within the assembly.

Accessing Static Members of Static Members

Consider the following classes
class A
{
public static int i;
}
class B
{
public static A a{get;}=new A(); // without new A(), B.A will be null
}
now,
B.a gives a new instance of A and since the variable "i" of class A is static, I can not access "i" through B.a i.e B.a.i is compile time error.
I understand that if I do like below,
class B
{
static class A
{
static int i;
}
}
then I could do B.A.i.
So my question is how could I access static members of a static member of a class? Is it possible at all and is there any other pattern that I can use.
Also note that making class "A" as static and having class "B" as
class B
{
public static A a{get;}
}
gives a compile time error that "static type cannot be used as return type".
Since i is static member of A you can access it directly like
class B
{
public static A a {get;} = new A();
public int ii{get;} = A.i;
}
how could I access static members of a static member of a class?
If something is a member of a class -- static or not static -- that means it's either a value or a reference to an instance of something. Therefore, if you know you have an instance of a class but that class has static members itself, then just access those members statically:
class MyClass
{
public static string Value { get; }
}
string x = MyClass.Value;
You don't need to instantiate a class to access it's static members.
Simply you can try :
int value = A.i;
If you need, you can add a static class too :
public static class A
{
public static int i;
}
and you can use anywhere in your code like :
int value = A.i;

How to get the name of class where an object is initialized c#

I have a few classes. Lets say:
public class A
{
public void SomeAction()
{
Debug.Write("I was declared in class: and my name is:");
}
}
And
public class B
{
public static A myClass = new A();
}
public class C
{
public static A myClass = new A();
}
public class D
{
public static A myClass = new A();
}
What I want "SomeAction" in class A to do is to print out which class it was initialized in.
So that for example in another class I called C.myClass.SomeAction(); it would print out "I was declared in class C my name is myClass"
I hope this makes sense.
The reasons im doing this is for debugging within automated testing. I understand its not the best way to do things but its a requirement of the business.
This requirement can be satisfied without inheritance or passing the object; we can get the name of the class that calls the constructor from within the body of the constructor by examining the stack.
public class A
{
private string _createdBy;
public void SomeAction()
{
Console.WriteLine("I was declared in class [{0}]", _createdBy);
}
public A()
{
var stackFrame = new StackFrame(1);
var method = stackFrame.GetMethod();
_createdBy = method.DeclaringType.Name;
}
}
In terms of performance, I am assuming that you are not creating many instances of these objects. You could also predicate this on whether you are doing a DEBUG build or on some other setting, so that this stuff is skipped entirely in your production executables.
Since you only reference an instance of class A in your other classes, I think there is no other way then setting a reference to the type which created class A, like eddie_cat already mentioned. You could do something like this:
public class B
{
public static A myClass = new A(typeof(B));
}
And then your class A would look like:
public class A
{
// store the parent type
private Type mParentClass;
// provide parent type during construction of A
public A(Type parentClass)
{
mParentClass = parentClass;
}
// note that method cannot be static anymore, since every instance of A might
// have a different parent
public void SomeAction()
{
// access field where parent type is stored.
Debug.Write("I was declared in class: {0} and my name is:",mParentClass.Name);
}
}
I think you have two choices. Either set a property in A, or inherit from A. Personally, I prefer inheriting from A, because then A could just use GetType().
public class A
{
public void SomeMethod()
{
Debug.Write(string.Format("I was declared in class: {0}",this.GetType()));
}
}
public class B : A
{
}
var instanceOfB = new B();
instanceOfB.SomeMethod();

Why is static int always 0 when accessed from another class

I have a class with a static int. I want that int, once set, to be accessible anywhere in my program.
public class MyClass
{
public static int myInt;
public MyClass()
{
myInt = 100;
new TestClass();
}
static void Main(string[] args)
{
new MyClass();
}
}
..but when I try to call it in another class
public class TestClass
{
public TestClass()
{
int testInt = MyClass.myInt;
}
}
..testInt is always 0, even when I check in debug mode and see that the static int was successfully set.
What am I doing wrong?
You never instantiate an instance of the class... so the constructor never gets fired.
What you want is a static constructor.. to initialize static members:
public class MyClass {
public static int myInt;
static MyClass() { // Static Constructor
myInt = 100;
}
}
A static constructor is guaranteed to be fired before any access to an object. Exactly when is undetermined.
Well either as #Simon Whitehead suggested or the best way for this kind of thing is to initialize it when declaring. So you can write it like this:
public static int myInt = 100;
as this is not dependent on anything else, you don't need to wait for constructor.
I can't see any problem in the OP, as the code indeed does the expected job:
Try adding Console.WriteLine(testInt); in the end of the TestClass constructor. If the code equals the one posted, it should output 100.

Categories

Resources