Unable to inherit constructor, An object reference is required - c#

Consider:
using System;
namespace TuristickaAgencija
{
public class World
{
protected char[] dest;
public World(char[] dest)
{
this.dest = dest;
}
}
class Client : World
{
private char[] name;
private char[] surname;
private int age;
private int noCounter;
private bool hasVehicle;
public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle) : base(dest)
{
this.name = name;
this.surname = surname;
this.age = age;
this.noCounter = noCounter;
this.hasVehicle = hasVehicle;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
I'm getting 2 errors:
An object reference is required for the non-static field, method or property 'World.dest'
Missing partial modifier on declaration of type 'Program'
I want all classes to be in the same file.

It's unclear what dest you are trying to pass the constructor of the base class. You can't pass a reference to a field of an instance that has not yet been instantiated.
You should either add a parameter to Client constructor and pass this one to the base constructor:
public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle,
char[] dest) : base(dest)
{
this.name = name;
this.surname = surname;
this.age = age;
this.noCounter = noCounter;
this.hasVehicle = hasVehicle;
}
Or you should pass some default value like for example null or an empty array:
public Client(char[] name, char[] surname, int age, int noCounter, bool hasVehicle) : base(default)

You need to pass a valid value in order to initialize dest.
dest is not defined in the csope of constructor yet, you are calling the base ctor and should intialzie it.
you can pass name, or surename or add another param and use it.
As for the partial error probably you have already a Program class defined somewhere else in your code and you cannot declare 2 classes with the same name.
hope this helps.

Related

class's output in C#, how to do

Here is my problem:
I want to output a value from a class when I call to its instance.
For example, I have a class like this:
class Car
{
public string name = null;
public int id;
public int horsepower;
public Car(int ID, string Name, int HorsePower)
{
this.id = ID;
this.name = Name;
this.horsepower = HorsePower;
}
}
I want the output will be "aventador lp700-4" when I have a program like this:
class Program
{
static void Main(string[] args)
{
Car car = new Car(1, "aventador lp700-4", 700);
////////////// I want the output will be "aventador lp700-4" /////////////////////
Console.WriteLine(car);
///////////////////////////////
Console.Read();
}
}
I find some dll library could do that, but I don't know how to to.
Console.WriteLine(object) wants to get a string for the object passed in; there are a few different ways it can do that, but the default (in the absence of you telling it something more specific) is that it is just going to call .ToString() on the argument. So: you need to override the ToString() method on Car, to tell it what you want to use to represent that type as a string:
class Car
{
// ... your existing code
public override string ToString() { return name; }
}
Override the ToString method in your car class
public override string ToString(){
return name;
}

c# obtaining property values from object

I am trying to use a method to create an object and return that object to main(). Once in main I want to be able to access the properties of that object such as print Holly.age. VS does not recognize the object Holly in main() to have any properties. Is anyone able to tell what I am doing wrong or let me know if it's not something possible in c#.
Thanks in advance to anyone who gives there time to help.
class program
{
static void Main(string[] args)
{
object Holly = createobject(Holly, 21);
int hollyage = Holly.age; // This Line is the problem Holly.age is not recognized
// as anything
}
public static object createobject(string name, int i)
{
Cat Holly = new Cat(name, i);
return Holly;
}
public class Cat
{
public string name;
public int age;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public Cat(string name, int age)
{
this.name = name;
this.age = age;
}
}
VS does not recognize the object Holly in main() to have any properties
This is because you have declared Holly to be object rather than Cat, and similarly your create routine returns object rather than Cat.
To be able to use any of the properties of Cat you need to cast Holly back to Cat or better still, return Cat from your create routine. Unless you intend to extend your create routine to do more, you don't really need it and can simply do:
Cat Holly = new Cat("Holly", 21);
You also have both public fields and public properties in your Cat class. The fields should be made private, but that's not the cause of the problem.
Your method createobject returns an object. So you must first cast it back into Cat before you can access Age:
int hollyage = ((Cat)Holly).Age;
In addition your call to the createobject is wrong. It requests a string. Change to:
createobject("Holly", 21);
The correct way to write your code would be:
static void Main(string[] args)
{
//variable name in camelCase.
//"Holly" is a string
object holly = CreateObject("Holly", 21);
//Casting from object to Cat so you can access Age property
int hollyAge = ((Cat)holly).Age;
}
//Function names EachWorkCapitalized
public static object CreateObject(string name, int i)
{
Cat holly = new Cat(name, i);
return holly;
}
public class Cat
{
//If you implement your properties with the default get set behavior
//better use automatically implemented properties
public string Name { get; set; }
public int Age { get; set; }
public Cat(string name, int age)
{
Name = name;
Age = age;
}
}
You don't actually need public static object createobject()
You can simply remove that and change your Main to:
static void Main(string[] args)
{
Cat Holly = new Cat("Holly", 21);
int hollyage = Holly.age;
}
The problem is that Holly is defined as an object class, and object classes do not have an age or Age property.
You should change the line as:
Cat Holly = createObject("Holly", 21) as Cat;
Then the intellisense will recognize the Holly variable as being of type Cat.
You could always cast the object to the correct type to access it's members.
int hollyage = ((Cat)Holly).Age;

c# static class field and parameter with same name

As this.name is not working to access fields with the same name like a method parameter in static classes, I'm looking for a way to do so.
As an example i would like to do this:
static class test
{
private static string aString;
public static void method(string aString)
{
// aString (field) = aString (parameter)
}
}
use:
test.Astring = x;
i.e. replace this with the class name, test in this case.
static class test
{
private static string Astring="static";
public static void method(string Astring)
{
string passedString = Astring; // will be the passed value
string staticField = test.Astring; // will be static
}
}
if we call the method like test.method("Parameter"); the staticField will have the value static and passedString will have the value Parameter.
The keyword this denotes the current instance of the class; static
fields cannot be accessed through instance you should use the class
name instead for accessing the static field.
Note :- But please take care while naming the variables. Avoid giving same name in same class. It will be best if you define the class like the following
static class test
{
private static string StaticAstring="static";
public static void method(string passedAstring)
{
string staticField = StaticAstring; // will be static
string passedString = passedAstring; // will be the passed value
}
}

How to assign a value from a C# static method to a label

I have the following static function in c#
public static string Greet(string name)
{
string greeting = "welcome ";
// is it possible to pass this value to a label outside this static method?
string concat = string.Concat(greeting, name);
//error
Label1.text = concat;
//I want to return only the name
return name;
}
As you can see in the comments, I want to retain only the name as the return value, however I want to be able to take out the value of the concat variable to asign it to a label, but when i try the compiler refuses, can it be done? Is there a work around?
Thank you.
If the method must be static for some reason, the main approach here would be to pass any required state into the method - i.e. add a parameter to the method that is either the label or (better) some typed wrapper with a settable property like .Greeting:
public static string Greet(string name, YourType whatever)
{
string greeting = "welcome ";
whatever.Greeting = string.Concat(greeting, name);
return name;
}
(where YourType could be your control, or could be an interface allowing re-use)
What you don't want to do is use static state or events - very easy to get memory leaks etc that way.
For example:
public static string Greet(string name, IGreetable whatever)
{
string greeting = "welcome ";
whatever.Greeting = string.Concat(greeting, name);
return name;
}
public interface IGreetable {
string Greeting {get;set;}
}
public class MyForm : Form, IGreetable {
// snip some designer code
public string Greeting {
get { return helloLabel.Text;}
set { helloLabel.Text = value;}
}
public void SayHello() {
Greet("Fred", this);
}
}
Either non-static:
public string Greet(string name)
{
const string greeting = "welcome ";
string concat = string.Concat(greeting, name);
Label1.Text = concat;
return name;
}
Or still static passing the label like Greet("John", Label1):
public static string Greet(string name, Label label)
{
const string greeting = "welcome ";
string concat = string.Concat(greeting, name);
label.Text = concat;
return name;
}
But not sure why you need to return the name in either case...if you had it when calling the function, you already have it in the scope you'd be returning to. Example:
var name = "John";
Greet(name);
//can still call name here directly
The problem is that you try to instantiate a class variable from static method.
Maybe I'm missing the point but couldn't you just do:
public static string Greet(string name)
{
return string.Concat("Welcome ", name);
}
Then use it like:
string name = "John";
label1.Text = Greet(name);
Web methods do not have to be static.

Correct use of Properties to maintain a HUD in a nested Form?

Edit 1
Is it possible to do this with get/set? Something like the below? This works for me but I am worried I am missing something not to mention all the staticness.
///<summary>
/// Class to track and maintain Heads Up Display information
///</summary>
public static class HUD
{
///<summary>
///Declare variables to store HUD values
///</summary>
private static string _lastName;
private static string _firstName;
private static string _middleName;
private static string _suffix;
private static string _sSN;
private static string _personID;
private static string _masterID;
private static string _enrollmentID;
private static string _planID;
// Store a reference to THE form that holds the HUD and is visible
private static FrmModuleHost _frmHUDHost;
public static string PersonId
{
get { return _personID; }
set
{
FrmHudHost.tbxHUD_PersonID.Text = value;
_personID = value;
}
}
public static string SSn
{
get { return _sSN; }
set
{
FrmHudHost.tbxHUD_SSN.Text = value;
_sSN = value;
}
}
public static string MiddleName
{
get { return _middleName; }
set
{
FrmHudHost.tbxHUD_MiddleName.Text = value;
_middleName = value;
}
}
public static string FirstName
{
get { return _firstName; }
set
{
FrmHudHost.tbxHUD_FirstName.Text = value;
_firstName = value;
}
}
public static string LastName
{
get { return _lastName; }
set
{
FrmHudHost.tbxHUD_LastName.Text = value;
_lastName = value;
}
}
public static string Suffix
{
get { return _suffix; }
set
{
FrmHudHost.tbxHUD_SuffixName.Text = value;
_suffix = value;
}
}
public static string MasterID
{
get { return _masterID; }
set
{
FrmHudHost.tbxHUD_MasterID.Text = value;
_masterID = value;
}
}
public static string EnrollmentID
{
get { return _enrollmentID; }
set
{
FrmHudHost.tbxHUD_EnrollmontPeriod.Text = value;
_enrollmentID = value;
}
}
public static string PlanID
{
get { return _planID; }
set
{
FrmHudHost.tbxHUD_PlanID.Text = value;
_planID = value;
}
}
public static FrmModuleHost FrmHudHost
{
get { return _frmHUDHost; }
set { _frmHUDHost = value; }
}
}
Original Post
I have a class that is responsible for updating a Heads Up Display of current selected member info. My class looks like this -->
public static class HUD
{
///<summary>
///Declare variables to store HUD values
///</summary>
public static string _lastName;
public static string _firstName;
public static string _middleName;
public static string _suffix;
public static string _sSN;
public static string _personID;
public static string _masterID;
public static string _enrollmentPeriod;
public static string _planID;
///<summary>
/// Method to update the display with current information
///</summary>
public static void UpdateHUD (FrmModuleHost frm, params String[] args)
{
frm.tbxHUD_LastName.Text = args[0];
_lastName = args[0];
frm.tbxHUD_FirstName.Text = args[1];
_firstName = args[1];
frm.tbxHUD_MiddleName.Text = args[2];
_middleName = args[2];
frm.tbxHUD_SSN.Text = args[3];
_sSN = args[3];
frm.tbxHUD_PersonID.Text = args[4];
_personID = args[4];
}
}
What I am trying to figure out is how I can tell what args are being passed. What you see below is what is called from the Search Page as that is all that is available at that point. The other 4 values will be loaded 1 at a time on various pages. A person HAS A enrollment which HAS A plan if that helps.
private void GetResults()
{
var lName = getCurrentRowVal("Last Name");
var fName = getCurrentRowVal("First Name");
var pID = getCurrentRowVal("Person ID");
var sSN = getCurrentRowVal("SSN");
var mName = getCurrentRowVal("Middle Name");
HUD.UpdateHUD(FrmWwcModuleHost, lName, fName, mName, sSN, pID);
}
Now when I call this from the Enrollment Page I will want everything to stay and add the EnrollmentID.
private void GetResults()
{
var enrollmentID = getCurrentRowVal("EnrollmentID");
HUD.UpdateHUD(FrmWwcModuleHost, enrollmentID);
}
My question is, How do I do that and know which arg[] index to call and not overwrite the existing values?
Is it as simple as always providing ALL parameters as they are set? So my call from the Enrollment Page would instead look like this -->
private void GetResults()
{
var enrollmentID = getCurrentRowVal("EnrollmentID");
HUD.UpdateHUD(FrmWwcModuleHost, HUD._lastName, HUD._firstName, HUD._middleName, HUD._sSN, HUD._personID, enrollmentID);
}
Thanks for any insights!
You'll really need to ditch the params style call and establish real parameters for your methods. Just create multiple overloads for your most common call signatures.
I did not see a reference to a particular version of .net you are using. Here is how I handle this in .net 3.5.
First create a class for passing the update values in, but make all of the properties nullable (since all of your items are string, they are already nullable). If the values are nullable, add actual property setters, and LastNameChanged properties.
public class UpdateData {
public string LastName { get; set;};
public string FirstName { get; set;};
public string MiddleName { get; set;};
...
}
Now your method signature looks like this:
public static void UpdateHUD (FrmModuleHost frm, UpdateData data)
{
if (!string.IsNullOrEmpty(data.FirstName) {
frm.tbxHUD_LastName.Text = data.FirstName;
_lastName = data.FirstName;
}
if (!string.IsNullOrEmpty(data.LastName) {
frm.tbxHUD_FirstName.Text = data.LastName;
_firstName = data.FirstName;
}
if (!string.IsNullOrEmpty(data.MiddleName) {
frm.tbxHUD_MiddleName.Text = data.MiddleName;
_middleName = data.FirstName;
}
Next is the setting the UpdateData and calling the method:
UpdateHUD(FrmWwcModuleHost, new UpateData{ FirstName = "test1", LastName = "test2", ...});
Final note: you are using a lot of statics here. You might consider changing most of them. Move the static variables to an actual class with properties (but no statics), and reference the class in your code.
Perhaps instead of
params String[] args
you should do
params KeyValuePair<String,String>[] args
where any given param's properies would be assigned something like this:
Key = "Last Name"
Value = "Hare"
Then inside your UpdateHUD method you could check to see what the Key of the parameter was so you would know which value was being passed.
You could also create a separate class to pass in the params array. Something like:
public class HUDParam {
public HUDParam(paramName, paramValue) { /*[init code here...]*/ }
public string Name { get; set; }
public string Value { get; set; }
}
Then:
HUD.UpdateHUD(frm, new HUDParam("FirstName", "Tom"),
new HUDParam("LastName", "Thompson");
In your update method, you can just check the name and set the appropriate value in your HUD.
C# 4.0 has optional params which are much different from the params keyword. Params keyword is literally no different at runtime than if you didn't have the params keyword at all. In other words, you just get an array of values with no way of knowing which are which. Params keyword is just a C# convenience at compile time.
Although I haven't used C# 4.0 optional parameters yet, I imagine they behave similarly to the way VB.NET optional parameters did in that you can specify a default value at the function and that default will be used if the caller doesn't specify it. But the caller still has to indicate (either with missing values or paramName:= syntax) which parameter they are specifying.
In your case I think you're better off using either normal named parameters and passing null when you don't need them, or pass a dictionary/hashtable instead.
You could pass the arguments with a Dictionary where you can assign a value to a certain name.
The cleanest version would be to make a method for each variable.
e.g.
void UpdateLastName(string name)
{
frm.tbxHUD_LastName.Text = _lastName = name;
}
If you can use Framework 4.0, you can use optional and named parameters. Until that time, you will need to pass all the arguments.
But, I think by your question you might misunderstand what's happening slightly. The arguments you send in params are going into the method as an argument. Their scope therefore is the method itself, so you not "overwriting" anything. The array that you used for the first call is gone (out of scope) and the array you use for the second call will have whatever you put in it. Best way to do optional parameters before 4.0 is using multiple method overloads.
If you have a name association with a value but possibly unknown name values this is a candidate for a Dictionary .
Optional parameters involve no less checking than checking a dictionary if a key exists or if a member of a class is null. Since there already exists a primitive for this and it's more flexible I see no reason to use variable parameters or optional parameters.
What I would do is use an ananoymous type (which can be turned into a dictionary at runtime) and then changing the values which are present.
New function definition:
public static void UpdateHUD (FrmModuleHost frm, object args);
And client code:
UpdateHUD(frm, new {
MiddleName = "Jed",
SSN = "..." });
Using the code from Roy Osherove's Blog, this can be turned into a dictionary. The new implementation would be similar to:
var dictionary = MakeDictionary(args);
if ( dictionary.ContainsKey("SSN") ) { _sSN = dictionary["SSN"]; }
Of course, this will all be irrelevant when C# 4.0 comes out.

Categories

Resources