Set value of a static variable using a function - c#

I have declared some static variables in my solution as below,
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = "M23";
public static string ApproverlevelL2 = "Cre";
public static string ApproverlevelL3 = "Free34";
public static string ApproverlevelL4 = "CDF";
public static string ApproverlevelL5 = "FM";
}
}
My question is, If i try to set it the like below then i get the error as :
An object reference is required for the non-static field, method, or
property
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
}
}
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
So how can i achieve this?

Looks like you are trying to call an instance method (non-static) from a static property.
Try making your method static:
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}

Do you mean this:
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
private static string getLevel(string levelID)
{
string levelName;
logic here
return levelName;
}
}
}

If your issue is that you want the getLevel method to be in a different class, you could add a Function into your static class and override it with the method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static Func<string, string> getLevel = x => string.Empty;
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
public class WhateverClass
{
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// call this before accessing the fields in your Constants class
public void Init()
{
Constants.getLevel = x => getLevel(x);
}
}
}
The only reason I can think of to do this is maybe you have two applications using this static class and they need to get the level differently. Maybe one uses actual constant values and another reads a database, etc.
If you don't require this then the simplest answer is to actually put the method into the class as a static method:
namespace SSPWAS.Utilities
{
public class Constants
{
public static string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
}

Your "constants" are not constant. Make them readonly if you want them to behave like constants while making use of initialising static members with values. You could also make them properties and use just the get accessor to call the getLevel method.
As others have pointed out you cannot call a non-static member from within a static member, without instantiating an instance of the non-static class.
Your getLevel method also needs to be in its own class. As it stands it doesn't belong to a class or namespace. If you want it in its own separate class then just set the method to static.
.NET naming conventions recommend you use Pascal Casing for methods. So rename your getLevel method.
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = GetLevel("1"),
ApproverlevelL2 = GetLevel("2"),
ApproverlevelL3 = GetLevel("3"),
ApproverlevelL4 = GetLevel("4"),
ApproverlevelL5 = GetLevel("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => GetLevel("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return GetLevel("7"); } }
private static string GetLevel(string levelId)
{
//... do logic
return "";
}
}
}
Or if you want the method in its own class:
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = Level.Get("1"),
ApproverlevelL2 = Level.Get("2"),
ApproverlevelL3 = Level.Get("3"),
ApproverlevelL4 = Level.Get("4"),
ApproverlevelL5 = Level.Get("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => Level.Get("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return Level.Get("7"); } }
}
public class Level
{
public static string Get(string levelId)
{
//... do logic
return "";
}
}

Related

"} expected" error in c# program

I have made two classes in C# but when I created the constructor for the second class it gave me the error "} expected" I don't understand what is wrong as there are enough sets of {}. It also gives the same error for the very final curly brace at the bottom of the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cars
{
class Program
{
static void Main(string[] args)
{
Car c1 = new Car("Audi","A1","AB12 CDE",1985, 15000);
Console.WriteLine(c1);
string str = Console.ReadLine();
}
}
class Fleet
{
public Fleet()
{
public Car[] carArray = new Car[100];
}
}
class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string Registration { get; set; }
public int Year { get; set; }
public int Value { get; set; }
public Car(string make, string model, string registration, int
year, int value)
{
Make = make;
Model = model;
Registration = registration;
Year = year;
Value = value;
}
public override string ToString()
{
return string.Format("Make: {0}\nModel: {1}\nRegistration: {2}\nYear: {3}\nValue: {4:C}", Make, Model, Registration, Year, Value);
}
}
}
In your class
class Fleet
{
public Fleet()
{
public Car[] carArray = new Car[100];
}
}
you have carArray declared public but it's in the constructor. You can't have modifiers in methods. Any variable declared in a method is always only seen in the scope of that method. I'm assuming you need it in the class and not the constructor so just move it out like so...
class Fleet
{
public Car[] carArray = new Car[100];
public Fleet()
{
}
}
and all is good.
Above, in the "Fleet" class inisde the constructor you have tried to created an array object "carArray" along with initialization.
Because of this you are getting this error.
The constructor are meant for initialize the class variavles/objects, not for declaration of variavles/objects.
Try for this, it will work.
class Fleet
{
public Car[] carArray = null;
public Fleet()
{
carArray = new Car[100];
}
}

How to get const from static class C#?

I have static class with conts inside:
static class RestfulPaths {
static string BASE_URL = "A";
static string SYNC_CHECK = "A";
}
In another class I try to get const as:
RestfulPaths.BASE_URL
Make your class and its properties also public, then you'll get them from the other class.
public static class RestfulPaths
{
public static string BASE_URL = "A";
public static string SYNC_CHECK = "A";
}
public static class RestfulPaths {
public static string BASE_URL = "A";
public static string SYNC_CHECK = "A";
}

An object method is required for non static, field method

I've no experience of using C# but as part of one of our college modules we have to create a slot machine application. We created a Gambler class and I have to make a CheckBalance class where I will call the Token method from the Gambler class. But I get the error that is mentioned in the thread title.
Int tokens = Gambler.Tokens;
The above line is where I am getting my error.
This is my code:
enter code herenamespace CasinoClasslibrary
{
public class Gambler
{
public string Name { get; private set; }
public int Age { get; private set; }
public long CreditCardNum { get; private set; }
public int Tokens { get; public set; }
public string Username { get; private set; }
public string Password { private get; public set; }
public Gambler(string Name, int Age, long CreditCardNum, int Tokens, string Username, string Password)
{
this.Name = Name;
this.Age = Age;
this.CreditCardNum = CreditCardNum;
this.Tokens = Tokens;
this.Username = Username;
this.Password = Password;
}
}
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Gambler.Tokens;
return true;
}
}
}
Since you are inheriting from Gambler I suspect that you need to access base.Tokens like:
public Boolean CheckBalance()
{
int tokens = base.Tokens; //here
return true;
}
Otherwise since Toakens is an instance member you have to create object of Gambler and then access it.
There are other errors in your code as well. You haven't defined a default (parameter less) constructor in your base class and you need to call the existing base constructor in your child class.
public class Cashout : Gambler
{
public Cashout()
: base("",0, 0, 1, "", "") //something like this
{
}
public Boolean CheckBalance()
{
int tokens = base.Tokens;
return true;
}
}
Because Cashout inherits from Gambler you can just do this. This is because the Cashout instance will have a Tokens property as well.
public class Cashout : Gambler
{
public Boolean CheckBalance()
{
int tokens = Tokens;
return true;
}
}
However, if you intended the method to be static, you will need an instance of Gambler to access that property and this should be passed into the static method as such.
public class Cashout : Gambler
{
public static Boolean CheckBalance(Gambler myGambler)
{
int tokens = myGambler.Tokens;
return true;
}
}
Finally, if you intended this Tokens property to be static itself, you need to declare it as such
public static int Tokens;
You may also want a static constructor to set it up.
Tokens is not static method but you try to access it through static construct (class level).
can make this work by declaring it static (although that's not likely what you want)
public static int Tokens { get; public set; }
or by instantiating Gambler
new Gambler().Tokens;

Instantiating a class given a generic abstract type

Using this model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
#region Abstracts definitions
abstract class AnAbstract
{
public string Name { get { return this.GetType().Name; } }
public bool IsNumeric { get { return this is ANumericAbstract; } }
public /*abstract*/ string Description = default(string);
}
abstract class ANumericAbstract : AnAbstract
{
public /*abstract*/ double Min = double.MinValue;
public /*abstract*/ double Max = double.MaxValue;
}
abstract class ANonNumericAbstract : AnAbstract
{
public List<Object> objects = new List<Object>();
}
#endregion Abstracts definitions
#region Concrete definitions
class NumericImpl : ANumericAbstract
{
new public const string Description = "A numeric implementation";
new public const double Min = 0;
new public const double Max = 1000;
public NumericImpl()
{
}
}
abstract class AnotherImpl : ANonNumericAbstract
{
public AnotherImpl()
{
objects.Add("one");
objects.Add("two");
objects.Add("three");
}
}
class SideA : AnotherImpl
{
new public const string Description = "Disc side A";
}
class SideB : AnotherImpl
{
new public const string Description = "Disc side B";
}
#endregion Concrete definitions
partial class Parameter
{
public string Name { get; set; }
public string Description { get; set; }
public bool IsNumeric { get; private set; }
public double Min { get; private set; }
public double Max { get; private set; }
public List<Object> Values { get; private set; }
private Parameter()
{
Values = new List<Object>();
}
}
}
With this, I pretend to define a hierarchy of classes for which I can have some abstract properties (Name,Description,IsNumeric) and at the end of the hierarchy there should be some classes which mandatorily define those properties; in the case of ANumericAbstract they should have additional specific properties, e.g. Min and Max.
Now here's the problem.
I'm attemtping to be able to create instances of Parameter which take a generic AnAbstract and read from it some values to fill in the Parameter properties, à la
Parameter<ANumericAbstract> ParamNum = new Parameter<NumericImpl>();
where a Parameter constructor would take in the passed type and "fill in the blanks". In other words, I'm trying something like:
using System;
namespace ConsoleApplication1 {
partial class Parameter
{
public static Parameter NewParameter<T>() where T : AnAbstract
{
Parameter Parameter = new Parameter();
// THESE DON'T WORK:
this.Name = T.Name;
this.Description = T.Description;
this.IsNumeric = T.IsNumeric;
if (this.IsNumeric)
{
this.Min = (T as ANumericAbstract).Min;
this.Max = (T as ANumericAbstract).Max;
}
else
{
foreach(Object val in (T as ANonNumericAbstract).Values)
{
this.Values.Add(val);
}
}
return Parameter;
}
}
class Program
{
private AnAbstract Number = new NumericImpl();
static void Main(string[] args)
{
}
// THESE DON'T WORK:
private static Parameter<ANumericAbstract> ParameterNum =
Parameter.NewParameter<NumericImpl>();
private static Parameter<ANonNumericAbstract> ParameterA =
Parameter.NewParameter<SideA>();
private static Parameter<ANonNumericAbstract> ParameterB =
Parameter.NewParameter<SideB>();
}
}
Obviously the syntax is invalid, but I'm not sure if I'm going in the right direction. Is there some Generics syntax that I'm not using properly? Should I just be done with it and use Getters and Setters à la Java? :-) At this point, just doing the
Parameter par = new Parameter { Name = NumericImpl.Name, /* ... */ };
might seem more sensible...
Firstly you should not use New keyword on your properties.
Consider virtual keyword:
abstract class AnAbstract
{
public virtual string Name { get { return this.GetType().Name; } }
public virtual string Description { get { return String.Empty; } }
}
abstract class ANumericAbstract : AnAbstract
{
public virtual double Min = double.MinValue;
}
class NumericImpl : ANumericAbstract
{
public override string Description { get { return "A numeric implementation"; } }
public override double Min { get { return 0; } }
}
1) You can place an instance of you type in Parameter constructor and have Parameter instance.
partial class Parameter
{
public Parameter(AnAbstract inputObject)
{
this.Name = inputObject.Name;
// etc
}
}
private static Parameter ParameterNum = new Parameter(new NumericImpl());
2) The second way is to use reflection to create an instance of object with initial parameters.
partial class Parameter<T> where T : AnAbstract
{
public static Parameter<T> NewParameter<T>() where T : AnAbstract
{
Parameter<T> parameter = new Parameter<T>();
AnAbstract instance = (AnAbstract)Activator.CreateInstance(typeof(T));
parameter.Name = instance.Name;
// etc
return parameter;
}
}
private static Parameter<NumericImpl> ParameterNum =
Parameter<NumericImpl>.NewParameter();
3) Make Parameter class static and create in via static constructor.
static partial class Parameter<T> where T : AnAbstract
{
public static string Name { get; set; }
//etc
}
static partial class Parameter<T> where T : AnAbstract
{
static Parameter ()
{
AnAbstract instance = (AnAbstract)Activator.CreateInstance(typeof(T));
Parameter<T>.Name = instance.Name;
//etc
}
}
In the last example you can use this class like this:
String someName = Parameter<NumericImpl>.Name;

Calling a Variable from another Class

How can I access a variable in one public class from another public class in C#?
I have:
public class Variables
{
static string name = "";
}
I need to call it from:
public class Main
{
}
I am working in a Console App.
That would just be:
Console.WriteLine(Variables.name);
and it needs to be public also:
public class Variables
{
public static string name = "";
}
I would suggest to use a variable instead of a public field:
public class Variables
{
private static string name = "";
public static string Name
{
get { return name; }
set { name = value; }
}
}
From another class, you call your variable like this:
public class Main
{
public void DoSomething()
{
string var = Variables.Name;
}
}
You need to specify an access modifier for your variable. In this case you want it public.
public class Variables
{
public static string name = "";
}
After this you can use the variable like this.
Variables.name
class Program
{
Variable va = new Variable();
static void Main(string[] args)
{
va.name = "Stackoverflow";
}
}

Categories