How do I call static from the class I created in c# - c#

namespace HelloDogs
{
class Dog
{
private string barkSound;
private string breed; // Added dogHeight, dogColor and noOfLegs to
private int dogHeight; // the private variable
private string dogColor;
private static int noOfLegs;
public string Breed
{
get { return breed; }
set { breed = value; }
}
public static int NoOfLegs
{
get{return noOfLegs; } // I created properties to encapsulate the variables
set {noOfLegs = value; } // dogHeight, dogColor and noOfLegs using the properties
}
public int DogHeight
{
get {return dogHeight;}
set{dogHeight = value;}
}
public string DogColor
{
get {return dogColor;}
set{ dogColor = value;}
}
private string dogSpeech;
public Dog()
{
barkSound = "Jack!";
breed = "cocker spaniel";
}
// Added a new constructor below that takes the following parameters
public Dog(int h,string b, string c )
{
dogHeight = h;
dogColor = c;
breed = b;
}
// A private method to check the dogHeight if true or false
private bool IsBig(int x)
{
if (x < 50)
return false;
else
return true;
}
// Change the GetSpeech method below to display all details about the dog
public string GetSpeech()
{
dogSpeech = "Hello, I am a " + breed + " , " + dogHeight + "cm" + ","
+ dogColor + "." + barkSound ;
return dogSpeech;
if(IsBig(dogHeight))
{
return dogSpeech = "You are big ";
} else
{
dogSpeech = " You are not big enough";
}
}
public void SetSound(String barkSound)
{
this.barkSound = barkSound;
}
}
}

Calling static from class please see this in msdn
https://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Related

c# using other class method

Thanks to NHMountainGoat for an answer!
Implementing Interface looks a good choice so we have only the 'needed' method instanciated.
It looks like this now:
EDIT
class Machine
{
//REM: MachineConnexion is a link to the main server where asking the data
internal linkToPLC LinkToPLC;
public IlinkToPLC ILinkPLC;
public interface IlinkToPLC//Interface to linkPLC
{
Int16 MachineNumIS { get; set; }
}
internal class linkToPLC : IlinkToPLC
{
private Int16 Act_MachineNum;
private List<string> genlnkPLCCanvas;
private List<string> genlnkPLCworkingwith;
static private List<string> ListSymbolNoExist;
private string[] ListToPLClnk = {
"GlobalFolder.PMachine[{0}].",
"GlobalFolder.PMachine[{0}].STATE.",
"GlobalFolder.Machine[{0}].",
"GlobalFolder.Machine[{0}].STATE.",
};
public linkToPLC()//ctor
{
genlnkPLCCanvas = new List<string>(ListToPLClnk);
genlnkPLCworkingwith = new List<string>(ListToPLClnk);
ListSymbolNoExist = new List<string>();
Act_MachineNum = MachineNumIS;
}
public Int16 MachineNumIS { get { return (Int16)ReadWriteMachine("data"); } set { ReadWriteMachine("data", value); } }
public string ValueExist(string ValueToreach, bool WorkingDATA = false)
{
if (!WorkingDATA)
{
for (int inc = 0; inc < genlnkPLCworkingwith.Count; inc++)
{
string StrValueToReach = genlnkPLCworkingwith[inc] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[inc] + ValueToreach);
}
}
else if (WorkingDATA)
{
string StrValueToReach = genlnkPLCworkingwith[10] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[10] + ValueToreach);
}
if (ListSymbolNoExist.Count != 0)
{
string ErrorList = "";
for (int inc = 0; inc < ListSymbolNoExist.Count; inc++)
{
ErrorList = string.Concat(ErrorList + "Num: " + inc.ToString() + " " + ListSymbolNoExist[inc].ToString() + "\n");
}
Console.WriteLine("Error" + ErrorList);
}
return null;
}
public object ReadWriteMachine(string VariableName, object DataToWrite = null, bool WorkingDATA = false)
{
string valueToFind = "";
if (ValueExist(VariableName) != "FALSE")
{
if (DataToWrite != null) { MachineConnexion.WriteSymbol(valueToFind, DataToWrite); }
return MachineConnexion.ReadSymbol(valueToFind);
}
return VariableName;
}
}
public Machine() //constructor
{
LinkToPLC = new linkToPLC();
}
}
And It doesn't work telling me that the reference object is not defined to an instance of the object..... in the line : Machine() LinkToPLC = new linkToPLC();//REM I found the bug, it was me ;o)) 24112016
//REM 24112016
What are the main differences between those two concept: static Instance and Interface?
Example:
class Program
{
static void Main(string[] args)
{
ITestInterface InterInstance = new TestInterface();
//test Interface
bool value1 = true;
value1 = InterInstance.invert(value1);
InterInstance.print(value1);
//test Instance static
TestStaticInstance staticInstance = new TestStaticInstance();
staticInstance.Instance.invert(value1);
staticInstance.Instance.print(value1);
Console.ReadKey();
}
}
class TestInterface : ITestInterface
{
public bool invert(bool value)
{
return !value;
}
public void print(bool value)
{
Console.WriteLine(value.ToString()+"\n");
}
private void methodX()
{ }
}
interface ITestInterface
{
bool invert(bool value);
void print(bool value);
}
public class TestStaticInstance
{
public TestStaticInstance Instance;
public TestStaticInstance()
{
Instance = this;
}
internal bool invert(bool value)
{
return !value;
}
internal void print(bool value)
{
Console.WriteLine(value.ToString());
}
}
Thanks
Can you structure your other classes to take an instance of the link class? See:
/// <summary>
/// just a stub to demonstrate the model
/// </summary>
internal class Machine
{
public string ReadData() { return "this is data"; }
public void WriteData(string data) { Console.WriteLine(data); }
}
internal interface IMachineDataAccessor
{
string Read();
void Write(string data);
}
class LinkClass : IMachineDataAccessor
{
protected Machine _machine;
public LinkClass(Machine machine)
{
_machine = machine;
}
public void DoMyWork()
{
// insert work somewhere in here.
string dataFromMachine = Read();
Write("outbound data");
}
public string Read()
{
return _machine.ReadData();
}
public void Write(string data)
{
_machine.WriteData(data);
}
}
class PersistentClass
{
IMachineDataAccessor _machineImpl;
public PersistentClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
class StateClass
{
IMachineDataAccessor _machineImpl;
public StateClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
static void Main(string[] args)
{
LinkClass link = new LinkClass(new Machine());
PersistentClass persistent = new PersistentClass(link as IMachineDataAccessor);
StateClass state = new StateClass(link as IMachineDataAccessor);
persistent.DoMyWork();
state.DoMyWork();
link.DoMyWork();
}

Why isn't my property doing the check?

My constructor get info from the form. The 'name' is addressed with 'aName' (from the constructor), then there has to be a check done with prop 'NameCheck'. but if I compile it, it return an empty string. Any ideas?
Code:
---- Class ----
//Fields
private List<Create> Characters;
private string name;
private int health;
private int mSpeed;
private Role role;
private Speciality speciality;
//Properties
public string NameCheck
{
get {
return name;
}
set
{
if (string.IsNullOrEmpty(name))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
//Constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.name = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
---- Form ----
Create character = new Create(tbName.Text, health, mspeed, aLane, aSpecial);
Characters.Add(character);
cbSummary.Items.Add(character.ToString());
PS: cbSummary is a combobox.
EDIT:
public override string ToString()
{
return "Name: " + NameCheck + " - Health: " + health + " - MovementSpeed: " + mSpeed + " - Role: " + role + " - Speciality: " + speciality;
}
You should set this.NameCheck instead of this.name in your constructor
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
also you should check value for emptiness or being null instead of name in your property setter
set
{
if (string.IsNullOrEmpty(value))
{
You have a small typo in your property:
public string NameCheck
{
get {
return name;
}
set
{
// You need to check value, not name.
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}
In your constructor you should use your NameCheck property rather than the name field:
public Create(string aName, int aHealth, int aMSpeed, Role aRole, Speciality aSpeciality)
{
this.NameCheck = aName;
this.health = aHealth;
this.mSpeed = aMSpeed;
this.role = aRole;
this.speciality = aSpeciality;
Characters = new List<Create>();
}
Also as Paddy said you are doing an incorrect check in the set body of NameCheck:
public string NameCheck
{
get
{
return name;
}
set
{
if (string.IsNullOrEmpty(value))
{
name = "Name not specified";
}
else
{
name = value;
}
}
}

That name doesn"t exist in the current context error

In public static void ammount() I get an error saying:
"The name 'mps' does not exist in the current context"
How do I fix this error?
struct mp3players{
private int ID;
private string Make;
private string Model;
private int MBSize;
private double Price;
private int vr;
public int id
{
get { return this.ID; }
set { this.ID = value; }
}
public string make
{
get { return this.Make; }
set { this.Make = value; }
}
public string model
{
get { return this.Model; }
set { this.Model = value; }
}
public int mbsize
{
get { return this.MBSize; }
set { this.MBSize = value; }
}
public double price
{
get { return this.Price; }
set { this.Price = value; }
}
public int VR
{
get { return this.vr; }
set { this.vr = value; }
}
}
public static void mp3()
{
mp3players mp1 = new mp3players();
mp1.id = 1;
mp1.make = "GET technologies .inc";
mp1.model = "HF 410 ";
mp1.mbsize = 4096;
mp1.price = 129.95;
mp1.VR = 500;
mp3players mp2 = new mp3players();
mp2.id = 2;
mp2.make = "Far & Loud";
mp2.model = "XM 600 ";
mp2.mbsize = 8192;
mp2.price = 224.95;
mp2.VR = 500;
mp3players mp3 = new mp3players();
mp3.id = 3;
mp3.make = "Innotivative";
mp3.model = "Z3 ";
mp3.mbsize = 512;
mp3.price = 79.95;
mp3.VR = 500;
mp3players mp4 = new mp3players();
mp4.id = 4;
mp4.make = "Resistance S.A.";
mp4.model = "3001 ";
mp4.mbsize = 4096;
mp4.price = 124.95;
mp4.VR = 500;
mp3players mp5 = new mp3players();
mp5.id = 5;
mp5.make = "CBA";
mp5.model = "NXT volume ";
mp5.mbsize = 2048;
mp5.price = 159.05;
mp5.VR = 500;
ArrayList mps = new ArrayList();
mps.Add(mp1);
mps.Add(mp2);
mps.Add(mp3);
mps.Add(mp4);
mps.Add(mp5);
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Make: " + value.make);
Console.WriteLine("Model: " + value.model);
Console.WriteLine("MBSize: " + value.mbsize);
Console.WriteLine("Price: " + value.price);
Console.WriteLine();
}
}
This is where the error occurs.
I tried a couple of ways but did not find what I was searching for.
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
I am not very good in C# so an explanation what I did wrong is also very welcome!
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
this code has knowledge of mps.
you would add a parameter the method so public static void ammount() looks like public static void ammount(mp3players[] mps). that will fix this error but cause another
you will have to pass mps into the method.
mps is a local variable inside mp3() method. It is not a global variable, so its not accessible in ammount() method.
I got your point , you are getting compilation error The name 'mps' does not exist in the current context. So to fix this, you have to make mps as global variable and set that value in mp3() method, and use that in other methods as well.
struct mp3players
{
private int ID;
private string Make;
private string Model;
private int MBSize;
private double Price;
private int vr;
public int id
{
get { return this.ID; }
set { this.ID = value; }
}
public string make
{
get { return this.Make; }
set { this.Make = value; }
}
public string model
{
get { return this.Model; }
set { this.Model = value; }
}
public int mbsize
{
get { return this.MBSize; }
set { this.MBSize = value; }
}
public double price
{
get { return this.Price; }
set { this.Price = value; }
}
public int VR
{
get { return this.vr; }
set { this.vr = value; }
}
}
private static ArrayList mps;
public static void mp3()
{
mp3players mp1 = new mp3players();
mp1.id = 1;
mp1.make = "GET technologies .inc";
mp1.model = "HF 410 ";
mp1.mbsize = 4096;
mp1.price = 129.95;
mp1.VR = 500;
mp3players mp2 = new mp3players();
mp2.id = 2;
mp2.make = "Far & Loud";
mp2.model = "XM 600 ";
mp2.mbsize = 8192;
mp2.price = 224.95;
mp2.VR = 500;
mp3players mp3 = new mp3players();
mp3.id = 3;
mp3.make = "Innotivative";
mp3.model = "Z3 ";
mp3.mbsize = 512;
mp3.price = 79.95;
mp3.VR = 500;
mp3players mp4 = new mp3players();
mp4.id = 4;
mp4.make = "Resistance S.A.";
mp4.model = "3001 ";
mp4.mbsize = 4096;
mp4.price = 124.95;
mp4.VR = 500;
mp3players mp5 = new mp3players();
mp5.id = 5;
mp5.make = "CBA";
mp5.model = "NXT volume ";
mp5.mbsize = 2048;
mp5.price = 159.05;
mp5.VR = 500;
mps = new ArrayList();
mps.Add(mp1);
mps.Add(mp2);
mps.Add(mp3);
mps.Add(mp4);
mps.Add(mp5);
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Make: " + value.make);
Console.WriteLine("Model: " + value.model);
Console.WriteLine("MBSize: " + value.mbsize);
Console.WriteLine("Price: " + value.price);
Console.WriteLine();
}
}
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
The variable 'mps' declared inside the function public static void mp3() and you are trying to access the same from another function public static void ammount() which can't be feasible due to the scope.
To access the 'mps' you have to remove the declaration from the mp3() function and move it directly uder you so defined class:
public class MySongColl
{
private static ArrayList mps = new ArrayList();
struct mp3players
{
....
....
}
public static void mp3()
{
....
....
}
public static void ammount()
{
....
....
}
}
NOTE:
Use proper Naming convention while you write code. e.g: Speeling mistake in Function name ammount() should be amount(). And use camel case while declaring the names like struct mp3players should be Mp3Players etc. These are not necessary to build the code but essential for a developer.

C# Inconsistent accessibility error

I am having trouble to fix the errors in my object oriented program in C#. The program has 9 classes and in the one class. The Error is Inconsistent accessibility: parameter type 'Employee.Employee' is less accessible than method 'Employee.EmployeeInput.CollectEmployeeInfo(Employee.Employee)'
on the coding
public static void CollectEmployeeInfo(Employee theEmployee)
{
theEmployee.Firstname = InputUtilities.getStringInputValue("First Name");
theEmployee.Lastname = InputUtilities.getStringInputValue("Last name");
theEmployee.Gender = InputUtilities.getCharInputValue("Gender");
theEmployee.Dependents = InputUtilities.getIntegerInputValue("# Dependents");
}
the CollectEmployeeInfo is what is showing the error and I am not sure what has to be done to the other classes to fix the error. Any help would be greatly appreciated
class Employee
{
public const double MIN_SALARY = 20000;
public const double MAX_SALARY = 100000;
public const int MIN_DEPENDENTS = 0;
public const int MAX_DEPENDENTS = 10;
public const string DEFAULT_NAME = "not given";
public const char DEFAULT_GENDER = 'U';
public const string DEFAULT_TYPE = "Generic Employee";
protected string firstName;
protected string lastName;
protected double annualSalary;
protected char gender;
protected int dependents;
protected static int numEmployees = 0;
protected Benefits employeeBenefits;
protected string employeeType;
public Employee()
{
firstName = DEFAULT_NAME;
lastName = DEFAULT_NAME;
annualSalary = MIN_SALARY;
dependents = MIN_DEPENDENTS;
numEmployees++;
employeeBenefits = new Benefits();
}
public Employee(string firstname, string lastname, char gender, int dependents, double annualsalary, Benefits employeeBenefits)
{
Firstname = firstname;
Lastname = lastname;
AnnualSalary = annualsalary;
Gender = gender;
Dependents = dependents;
EmployeeBenefits = employeeBenefits;
numEmployees++;
}
public Benefits EmployeeBenefits
{
get { return employeeBenefits; }
set
{
if (value == null)
employeeBenefits = new Benefits();
else
employeeBenefits = value;
}
}
public Employee(string employeeType)
: this()
{
EmployeeType = employeeType;
}
public string Firstname
{
get { return firstName; }
set
{
if (String.IsNullOrEmpty(value))
firstName = DEFAULT_NAME;
else
firstName = value;
}
}
public string Lastname
{
get { return lastName; }
set
{
if (String.IsNullOrEmpty(value))
lastName = DEFAULT_NAME;
else
lastName = value;
}
}
public double AnnualSalary
{
get { return annualSalary; }
set
{
if (value > MIN_SALARY & value < MAX_SALARY)
annualSalary = value;
else if (value < MIN_SALARY)
annualSalary = MIN_SALARY;
else
annualSalary = MAX_SALARY;
}
}
public char Gender
{
get { return gender; }
set
{
if (value == 'F')
gender = value;
else if (value == 'f')
gender = value;
else if (value == 'M')
gender = value;
else if (value == 'm')
gender = value;
else
gender = DEFAULT_GENDER;
}
}
public int Dependents
{
get { return dependents; }
set
{
if (value >= MIN_DEPENDENTS & value <= MAX_DEPENDENTS)
dependents = value;
else if (value < MIN_DEPENDENTS)
dependents = MIN_DEPENDENTS;
else
dependents = MAX_DEPENDENTS;
}
}
public static int NumEmployees
{
get { return numEmployees; }
}
public string EmployeeName
{
get { return firstName + " " + lastName; }
}
public string EmployeeType
{
get { return employeeType; }
set
{
if (String.IsNullOrEmpty(value))
employeeType = DEFAULT_TYPE;
else
employeeType = value;
}
}
public double CalculatePay()
{
return annualSalary / 52;
}
public double CalculatePay(double modifiedSalary)
{
AnnualSalary = modifiedSalary;
return AnnualSalary / 52;
}
public override string ToString()
{
string output;
output = "\n============ Employee Information ============";
output += "\n\t Type:\t" + employeeType;
output += "\n\t Name:\t" + firstName + " " + lastName;
output += "\n\t Gender:\t" + gender;
output += "\n\t Dependents:\t" + dependents;
output += "\n\tAnnual Salary:\t" + annualSalary.ToString("C2");
output += "\n\t Weekly Pay:\t" + CalculatePay().ToString("C2");
output += "\n\t" + employeeBenefits.ToString();
return output;
}
}
}
Employee type should be not less accessible than CollectEmployeeInfo.
So Employee should be defined as public "at least"
All of the types you need to pass to a method must be at least as accessible as that method. If Employee is a private or internal class it can't be passed to this method from outside that class/assembly.
Make Employee public and it should work.

Get the properties of objects in array

I have a small problem here.
I have an array which holds some objects (which have properties, duh)
Now I want to sort them by an int property that they have. My qustion is not how to sort them, but how do I read the value of the property of the objects in the array?
private void WriteHighscoreToFile(int groesse, int minenAnzahl, int zeit, string name)
{
using (StreamWriter sw = new StreamWriter(#"C:\Users\tstadler\Desktop\Highscore.txt", true))
{
sw.WriteLine("Spieler: " + name + " Punkte: " + (groesse * minenAnzahl - zeit * 2) + " Groesse: " + groesse + " Minenanzahl " + minenAnzahl + " Zeit: " + zeit);
}
using (StreamReader sr = new StreamReader(#"C:\Users\tstadler\Desktop\Highscore.txt", true))
{
List<CreateNewHighscore> highScores = new List<CreateNewHighscore>();
while (sr.ReadLine() != null)
{
_objectProperties = sr.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
highScores.Add(new CreateNewHighscore(_objectProperties));
highscoreCount++;
}
_highscoresArray = highScores.ToArray();
vergleicheArray(_highscoresArray);
}
}
The Class:
public class CreateNewHighscore
{
public string _name;
public int _punkte;
public int _groesse;
public int _minenAnzahl;
public int _zeit;
public CreateNewHighscore(string[] infos)
{
_name = infos[1];
_punkte = int.Parse(infos[5]) * int.Parse(infos[7]) - 2 * int.Parse(infos[9]);
_groesse = int.Parse(infos[5]);
_minenAnzahl = int.Parse(infos[7]);
_zeit = int.Parse(infos[9]);
} }
My qustion is not how to sort them, but how do I read the value of the property of the objects in the array?
You expose it as a property; for example:
class CreateNewHighscore
{
string _name;
int _punkte, _groesse, _minenAnzahl, _zeit;
public string Name { get { return _name; } }
public int Punkte { get { return _punkte; } }
public int Groesse { get { return _groesse; } }
public int Zeit { get { return _zeit; } }
public int MinenAnzahl { get { return _minenAnzahl; } }
// constructor not shown
}
Then you can access that member from any array / list; for example:
highScores.Sort((x,y) => x.Punkte.CompareTo(y.Punkte));
or:
int firstPunkte = _highscoresArray[0].Punkte;
Your array is of type CreateNewHighscore[] so if you want to access property in classic way just use following line.
_highscoresArray[i].YourIntProperty
where "YourIntProperty" is desired int property.
Use LINQ OrderBy method:
_highscoresArray = highScores.OrderBy(h => h.Punkte).ToArray();
Where Punkte is a property of your CreateNewHighscore class:
public int _punkte; // public field
public Punkte // public property
{
get { return _punkte; }
set { _punkte = value; } // you may not need setter
}
BTW currently your class DO NOT have any properties. There are only public (after your last edit) fields. If you want to sort by field value then:
_highscoresArray = highScores.OrderBy(h => h._punkte).ToArray();
But I advice you to make fields private, or use auto implemented properties instead. And rename your class. Name is really awful and sounds like method name.
public class CreateNewHighscore
{
public string Name { get; private set; }
public int Punkte { get; private set; }
public int Groesse { get; private set; }
public int MinenAnzahl { get; private set; }
public int Zeit { get; private set; }
public CreateNewHighscore(string[] infos)
{
// check infos count
Name = infos[1];
Punkte = int.Parse(infos[5]) * int.Parse(infos[7]) -
2 * int.Parse(infos[9]);
Groesse = int.Parse(infos[5]);
MinenAnzahl = int.Parse(infos[7]);
Zeit = int.Parse(infos[9]);
}
}

Categories

Resources