Passing private variable to base class constructor - c#

I want to pass a value to the base class constructor. The problem which I am facing is that the value is stored in a private variable inside derived class. Is it possible to pass it? or is it a good approach to do like this?
This is what I tried
class Filtering : Display
{
private int length = 10000;
public Filtering():base(length)
{
}
}
It is showing
An object reference is required for non-static field, method or
property
Base class
abstract class Display
{
public Display(int length)
{
}
}

Exactly as answerer Chips_100 wrote in his answer (currently deleted by owner):
If you want length to be an instance variable, but still supply it to the base constructor, I would suggest something like the following:
private const int DefaultLength = 10000;
private int length = DefaultLength;
public Filtering() : base(DefaultLength)
{
}
I haven't seen any indication the original author of this answer is inclined to undelete his own post. At the same time, while I would have written basically the same thing, I'd rather not take credit for an answer already present, authored by someone else. So I've converted this to a Community Wiki answer.

Related

Access Parent/Owning class variable from composed class?

Forgive me because I know my wording is terrible. I'll just give an example.
public class MainClass{
public int someVariable;
public List<HasAClass> cList = new List<HasAClass>();
addHasAClass(HasAClass c){
cList.Add(c);
}
}
public class HasAClass{
public HasAClass(){
//Modify someVariable in some way????
}
}
public class HasASubClass : HasAClass{
public ComposedClass(){
//Modify someVariable in some way???
}
}
I having trouble finding the right words for this questions but here is what I am trying to do:
I am creating an aid for an RPG similar to dungeons and dragons. Each character can have a variety of special abilitys which can effect the characters in some way (both negative and positive). I am trying do this with a variety of subclasses which store the pertinent info and get added to the character at varying points in time. What I can't figure out is how to modify the properties of the Character(I called it Main Class in my example) when instances of the HasA class are added to it.
The HasAClass needs a reference to the owning instance, so that it can ask the parent for values and update them when required...
public class HasAClass
{
private MainClass _mainClass;
public HasAClass(MainClass mainClass)
{
_mainClass = mainClass;
_mainClass.someVaraible = 42;
}
}
You then need to pass the owner reference into the constructor of the HasAClass when they are created. If this is not possible at the time of creating the instance then you would instead need to assign it as a property after it has been created. Such as inside the addHasAClass method.

Is it better to use this. before code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I sometimes need to go online and find a tutorial for something. I am often finding that some people put code like this:
this.button1.Text = "Random Text";
Then I find code that is just like this:
button1.Text = "Random Text";
Is it better to use the this.whatever or does it not matter?
It depends. Here's an example class:
class A
{
private int count;
public A(int count)
{
this.count = count;
}
}
In this case, the "this." is mandatory because it disambiguates the reference on the left of the assignment. Without it, it is not clear to you reading the code whether "count" would refer to the parameter or the field. (It is clear to the compiler, which has rules to follow.) But in most cases, it is purely a matter of preference.
Write all your code to emphasize salient points to the reader. If you feel that it is important for the reader to clearly understand that an identifier refers to an instance member then use this. If you feel that its an unimportant and distracting implementation detail, don't. Use good judgment to make your code readable.
this is just to make it clear, in some cases we have to use this:
Differentiate between parameter and local member:
//local member
object item;
private void SomeMethod(object item){
this.item = item;//must use this
}
Pass the current class instance into another method:
public class SomeClass {
private void SomeMethod(SomeClass obj){
//....
}
private void AnotherMethod(){
SomeMethod(this);//pass the current instance into SomeMethod
//.....
}
}
Use in extension methods:
public static class SomeClassExtension {
public static void SomeClassMethod(this SomeClass obj){
//use obj as a reference to the object calling this method...
}
}
Call a constructor from another constructor (with different signature):
public Form1(string s) : this() {//Call the Form1() before executing other code in Form1(string s)
//......
}
Use for declaring indexers:
public class SomeClass {
//declare an index returning a string
public string this[int index] {
get {return ...}
set { ... }
}
}
Use auto-properties in struct:
public struct SomeStruct {
public object AutoProp1 {get;set;}
public object AutoProp2 {get;set;}
public SomeStruct() : this() //must use this
{
AutoProp1 = someObject;
AutoProp2 = someObject;
}
}
Cast the current instance to the based classes/types:
public class ClassB : ClassC {
//...
}
public class ClassA : ClassB {
public ClassA(){
((ClassC)this).MemberOfClassC ... ;//There might be some member in ClassC
//which is overridden in ClassA or ClassB, casting to ClassC can help we invoke the original member instead of the overridden one.
}
}
There might be some other uses of this, however I'll update later if I think out.
It does not matter, it is a matter of style. I tend to omit this, since it is just extra code to mentally parse.
The only case it matters is when there is a naming conflict between local and instance variables, in which case this can be used to disambiguate between a field and a local variable.
Here is an example of the type of situation where it does matter:
public class Foo
{
private string x;
public Foo(string x)
{
// x = x; Assigns local parameter x to x, not what we want
this.x = x; // Assigns instance variable x to local parameter x: this disambiguates between the two.
}
}
an example of using this can be to access class variable when you already have a similar variable in the scope. Otherwise it is mostly of choice.
Example
public class Test
{
public string firstName { get; set; }
public void temp(string firstName)
{
firstName = this.firstName;
}
}
In regards to fields the only case where this is explicitly needed is when there is a naming conflict:
public class Foo
{
private string bar;
public Foo(string bar)
{
this.bar = bar;
}
}
So some will prepend an underscore:
public class Foo
{
private string _bar;
public Foo(string bar)
{
_bar = bar;
}
}
Usually it will not matter. This reason why you might use this. is to explicit say that you want to reference a property/field that belong to the current class.
Again, there are not many occasions when you are likely to need this, but for example you might have a local variable with the same name as a class level property/field. Then you could use this..
For example:
class MyClass
{
string s = "1";
void MyFunction(string s)
{
//s = local value as passed in to function
//this.s = "1"
}
}
It doesn't usually matter. The this keyword "refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method."
Check out this article.
http://msdn.microsoft.com/en-us/library/dk1507sz.aspx
generally it doesn't matter, but if you pass in a variable called, say button1, to a class method that already has a member called button1, then you'll need to disambiguate which one you really meant.
This is probably why people now use this. to explicitly say which variable you meant, if you use this practice all the time, you'll not get it wrong in the few cases where its important.
Of course, you could ensure that all member variables are uniquely named, say with a prefix like m_, but that's fallen out of fashion nowadays, people prefer to write out this.
It really depends on the situation.
http://msdn.microsoft.com/en-us/library/dk1507sz(v=vs.80).aspx
To qualify members hidden by similar names
To pass an object as a parameter to other methods
To declare indexers
As others have already pointed out, it is useful in distinguishing field/property with method variables, One other place where this is required is to invoke Extension methods on current instance. For example this.ExtensionMethod(); would work, but not just ExtensionMethod();
Other than that, its a matter of personal choice, some call it redundant and some like to use it. It totally depends on you and your team.
Personally I like to use this with class members, specially for Forms method if working on code-behind of winform, like this.Close();
For more discussion when to use this see: When do you use the "this" keyword?

Creating a function for getting a variable value [duplicate]

This question already has answers here:
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 9 years ago.
Should I prefer getting variable from other class directly(int number = something.number;) or should I use a function for getting that number(like in example below)? What is the difference?
class someclass
{
private int number;
public float GetSomething()
{
return number;
}
}
class otherclass
{
someclass something;
private void somefunction()
{
int number = something.GetSomething();
}
}
The difference between using a field reference or a getter method is that if you create a method that you expect "client code" to use, then you can always change the method code later and the client will not have to change his code. If you use a field, then the client will have to update their code from using the field to using a method, if you decide that you want, for example, validation in the method. So, in short, it is better practice to use getter methods for future-proofing. However, in a language like C#, you can also use properties, which act like methods but look like fields, so you can have the best of both worlds: nice syntax (fields), and future-proofing (methods).
for that type of data, you'd better use a property :
class someclass
{
private int number;
public int Number
{
get {return number;}
set {number = value;}
}
}
then you can use someclass.Number anywhere else
Direct accessing to a class variable outside of a class is not a good practice so it's strongly recommended to use methods (also include properties).
When there is no direct access to your class variables, other classes can use it and whenever you change the internal structure of your class you can do it with less effort. Consider you class:
class someclass
{
// it's a field
private int number;
// it's a property
public int Number
{
get{return this.number;}
}
//or you can use method
}
EDIT: If after a while you found that it was better to change the number's type to int?, you can do it because never outside the class anyone uses number so simply you can make changes to number and change your property this way
class someclass
{
private int? number;
public int Number
{
get{return this.number.Value;}
}
//or you can use method
}
Exposing fields is bad practice because it less extensive than expose method or property. For example you want to change this field's calculation logic depending on other fields values. That will be possible with both approaches but if you will use methods or properties it will be easier and cleaner to implement.

Using certain variables in different classes (C#)

I'm pretty new to C# and I was trying out a few things. I have a label (named 'newLabel') in the form1.cs. I have a class named 'methods.cs'. In this class I have the method
public static void updateLabel()
what I want to do is:
public static void updateLabel()
{
newLabel.Text = "New Value";
}
but this doesn't work, probably because the method is in methods.cs and the newLabel is in form1.cs.
I had the same problem with declared variables. In the methods.cs I had the variable
int value;
but I couldn't use this variable in form1.cs. I fixed this by doing
public static int value { get; set; }
I have no idea what that did but it works, but I don't know how I can apply this trick with the label.
Could someone help me with this?
Thanks!
You should read up about OOP and encapsulation. Basically you want the form
to access private fields in another object (your class) - this is restricted by encapsulation, that's why you are running into problem - you can get around them by adding those fields and methods to the "public" interface that your class is declaring by making them public properties and methods, i.e in your example:
public int Value {get;set;}
Sometimes composition is used, i.e. in your example since your class is directly accessing the form you could have a form property on your class:
public Form ViewForm {get;set;}
It would be best if you learnt C# from tutorials, but the answer to this particular question lies with something called "scope"
Essentially, scope is the visibility of variables, classes, functions and objects. A variable marked "private" can only be seen within the thing that created it (if it's created inside a function it will always be private and any variables defined inside a function can only be used inside that function). If it's created inside a class only that class can use it.
Variables or functions denoted as public (this can only be done inside a class) can be seen from outside that class. To do that you would invoke myClass.myVariable to access the variable or myClass.myFunction() to access the function.
To denote the visibility of an object you use the keywords "public" or "private". Note: This only applies to variables and functions inside classes (it also applies to other things within classes, such as nested classes and structs, but that's outside the scope of this basic intro).
for example:
class myClass
{
private int myInt;
public void myfunction()
{
myInt = 1;
}
}
This will work, as myInt can be seen by anything inside myClass
class myOtherClass
{
private void myfunction()
{
myClass myObject = new myClass();
myObject.myInt = 2;
}
}
This will not, as myInt is private to myObject and only myObject can change it. myOtherClass does not have permission and it cannot see it.
class myOtherClassTwo
{
private void myfunction()
{
myClass myObject = new myClass();
myObject.myFunction();
}
}
This, thankfully, will work. myFunction was set as public in the myClass class, so it can be seen by anybody outside of the class.
Now the keyword static which you use has a whole different meaning. I advise you not to use it until you've learned about it as you're only adding additional complexity to your problems.
I hope this has cleared things up, though I must urge you to follow some real tutorials as these basics must be thoroughly detailed or you'll be caught out later on.
Since your updateLabel method accesses the label inside the form, correct object-oriented design would dictate that this method should be in the form, too. Then you have no problem accessing newLabel.
Technically speaking: newLabel doesn’t mean anything outside a form object. You could have several copies of your form, which would mean several copies of your newLabel; which of them should it refer to? Of course the computer won’t take a guess there; it’ll expect that you tell it which form you want to use.
The reason you couldn’t access the value variable is because it was private. If you had changed it simply to:
public static int value;
then it would have worked.
From the Form1, call the updateLabel method in the mothods class:
methods updateMethod = new methods();
newLabel.Text = updateMethod.updateLabel();
With this method in the methods class:
public static string updateLabel(){
return "New Value";
}

Const vs protected static readonly

I've got a wrapper class which encapsulates a piece of information that needs to be transmitted as a byte array.
In that way, the class encapsulates the necessary header (with fields like DATA_LENGTH or MESSAGE_TYPE) into the corresponding byte positions. For that I want to define positions and length in constants, for example:
HEADER_DATA_LENGTH_IX = 0;
HEADER_DATA_LENGTH_LENGTH = 2;
which means DATA_LENGTH starts at 0 and takes two bytes.
but so far I'm struggling with making them constants or static readonly fields. Const cannot be protected, therefore I won't be able to derive a new class and change the constants if a use them, on the other way I might declare new constants in the derived class and the use them.
What will be your approach?
If you want to change the value of these params in a derived class, you can make them readonly and change them in the constructor of the derived class
I wouldn't make them const anyhow, because they're not...
The basic difference is when the variable is initialized. 'readonly' is set at initialization, or in the contructor, while 'const' is set at compile time.
I think the big decision is if you want to inherit the class and override the value. If you do, go readonly. Otherwise I don't think it really matters.
readonly C#ref: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
const C# ref: http://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx
Create an inner class with the constants. The deriving classes can then later override the inner class and change the constants as necessary.
e.g. base class:
public class Stuff
{
public class HeaderInformation
{
public const int HEADER_DATA_LENGTH_IX = 0;
public const int HEADER_DATA_LENGTH_LENGTH = 2;
}
}
Then the derived class can do this:
public class DerivedStuff : Stuff
{
public new class HeaderInformation : Stuff.HeaderInformation
{
public new const int HEADER_DATA_LENGTH_IX = 10;
}
}
This way, you have flexibility. In DerivedStuff, the HeaderInformation class has all of the constants in the base Stuff.HeaderInformation class, but can change any of them, or keep the ones it has.
This exact question is answered by the official c# faq on msdn
I wouldn't make these constant because they simply aren't constants. When declaring something as const you should ask yourself: can this change? Your message lengths might change one day, so they are better to be made readonly.

Categories