Creating a function for getting a variable value [duplicate] - c#

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.

Related

Passing private variable to base class constructor

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.

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?

c# getters setters style

I'm working on some code where there is lots of code like this:
private int x;
public void SetX(int new_x)
{
this.SetXValue(new_x);
}
private void SetXValue(int new_x)
{
this.x = new_x;
}
and similarly with properties:
private int x;
public int X
{
get { return this.GetX(); }
}
private int GetX()
{
return this.x;
}
What i don't get is why the need for the private methods which do the actual work, i.e. why not just have methods like this instead:
public void SetX(int new_x)
{
this.x = new_x;
}
public int X
{
get { return this.x; }
}
is it just the other persons personal choice or is there some good reason for using the first way?
(i typed above code manually so sorry if any mistakes but you should hopefully see what i'm trying to say)
Cheers
A
There's no reason for code like that as far as I can see. If you're not doing anything with the new values (like processing/checking before storing) and you're writing C# 3.0 you can actually just shorthand it it to this:
public int MyProperty { get; set; }
The compiler creates the backing store for you and you can just reference:
this.MyProperty
...inside your class. You can also create get-only properties like:
public int MyProperty { get; private set; }
All of which I think is pretty neat!
Why don't you use the Getters and Setters directly to implement your logic? I don't understand the need for additional methods unless you have extra parameters that influence the setter's behavior:
private int myVar;
public int MyProperty
{
get
{
return myVar;
}
set
{
myVar = value;
}
}
public void SetMyPropertySpecial(int a, string reason)
{
Console.WriteLine("MyProperty was changed because of " + reason);
this.myVar = a;
}
Update:
Indeed, this person seems to like having more lines of code, but the structure is utterly useless. Stick to .NET standards using Getters and Setters (see MSDN)
No, there is no reason for doing this, it looks liks someone was paid by lines of code.
So, yes, you're right, this is just the other persons personal choice, and it's not a very good one.
A general rule of thumb is to use properties for simple get/set operations and get/set methods when there is a relevant part of logic needed to get/set a value (e.g. validation during set or database access during get).
So if the actual code is really as simple as in your example just use properties and do the work in their getters/setters.
If the actual code is more complex replace the properties (at least the setters) by methods as in your third example.
One possible reason would be that the properties can have login that should be executed only when the property is set externally and calls from inside the class do not execute the whole logic but only the logic in the private method. Of course it makes no sense to make these methods in advance because introducing them later will not change the contract of the class. Chances are that whoever wrote this code was new to C# and did not understand what properties do.
I think it must be an old Java developper that did this.
The .Net way is
private int _foo;
public int Foo
{
get
{
return _foo;
}
set
{
_foo = value;
dostuff();
}
}
That's very bizarre, there's no justifiable reason for doing that. Please refactor that code. There's also no need for a SetX method as setter can be included in properties. e.g.:
public int X {get; set;}
i may be missing something here, but this looks a bit mad to me!
You can achieve the same by either using automatic properties or properties with backing fields. here's a good description of both: http://weblogs.asp.net/dwahlin/archive/2007/12/04/c-3-0-features-automatic-properties.aspx
Yes, that is fine only if the SetValue is private or protected and is doing more than just setting a value.
I am working on a project where we do a lot of those things. That is because we are doing more than just setting a value (value checks, state checks etc.)
Having a public setter and a public SetValue does not make sense at all and will confuse your consumers as to what setter to use.
Here is another scenario where we use this kind of design:
public abstract class A{
protected virtual void SetValue(object value);
public object SomeObject{
set{SetValue(value);}
}
}
In this case, we want class A to delegate setting/checking that value to whatever class inheriting from it.

Read-only ("const"-like) function parameters of C#

Coming from a C++ background, I'm used to sticking the const keyword into function definitions to make objects being passed in read-only values. However, I've found out that this is not possible in C# (please correct me if I'm wrong). After some Googling, I arrived at the conclusion that the only way to make a read-only object is to write an interface that only has 'get' properties and pass that in instead. Elegant, I must say.
public interface IFoo
{
IMyValInterface MyVal{ get; }
}
public class Foo : IFoo
{
private ConcreteMyVal _myVal;
public IMyValInterface MyVal
{
get { return _myVal; }
}
}
I would pass it into:
public void SomeFunction(IFoo fooVar)
{
// Cannot modify fooVar, Excellent!!
}
This is fine. However, in the rest of my code, I would like to modify my object normally. Adding a 'set' property to the interface would break my read-only restriction. I can add a 'set' property to Foo (and not IFoo), but the signature expects an interface rather than a concrete object. I would have to do some casting.
// Add this to class Foo. Might assign null if cast fails??
set { _myVal = value as ConcreteMyVal; }
// Somewhere else in the code...
IFoo myFoo = new Foo;
(myFoo as Foo).MyFoo = new ConcreteMyVal();
Is there a more elegant way of replicating const or making read-only function parameters without adding another property or a function?
I think you may be looking for a solution involving two interfaces in which one inherits from the other:
public interface IReadableFoo
{
IMyValInterface MyVal { get; }
}
public interface IWritableFoo : IReadableFoo
{
IMyValInterface MyVal { set; }
}
public class Foo : IWritableFoo
{
private ConcreteMyVal _myVal;
public IMyValInterface MyVal
{
get { return _myVal; }
set { _myVal = value as ConcreteMyVal; }
}
}
Then you can declare methods whose parameter type “tells” whether it plans on changing the variable or not:
public void SomeFunction(IReadableFoo fooVar)
{
// Cannot modify fooVar, excellent!
}
public void SomeOtherFunction(IWritableFoo fooVar)
{
// Can modify fooVar, take care!
}
This mimics compile-time checks similar to constness in C++. As Eric Lippert correctly pointed out, this is not the same as immutability. But as a C++ programmer I think you know that.
By the way, you can achieve slightly better compile-time checking if you declare the type of the property in the class as ConcreteMyVal and implement the interface properties separately:
public class Foo : IWritableFoo
{
private ConcreteMyVal _myVal;
public ConcreteMyVal MyVal
{
get { return _myVal; }
set { _myVal = value; }
}
public IMyValInterface IReadableFoo.MyVal { get { return MyVal; } }
public IMyValInterface IWritableFoo.MyVal
{
// (or use “(ConcreteMyVal)value” if you want it to throw
set { MyVal = value as ConcreteMyVal; }
}
}
This way, the setter can only throw when accessed through the interface, but not when accessed through the class.
The closest equivalent is the in keyword. Using in makes the parameter and input parameter and prevents it from being changed inside the method. From the official C# documentation:
in - specifies that this parameter is passed by reference but is only read by the called method.
ref - specifies that this parameter is passed by reference and may be read or written by the called method.
out - specifies that this parameter is passed by reference and must be written by the called method.
First of all, you're correct: you cannot apply const or a similar keyword to parameters in C#.
However, you can use interfaces to do something along those lines. Interfaces are special in the sense, that it makes perfect sense to make an interface that only covers a specific part of a feature set. E.g. image a stack class, which implements both IPopable and IPushable. If you access the instance via the IPopable interface, you can only remove entries from the stack. If you access the instance via the IPushable interface, you can only add entries to the stack. You can use interfaces this way to get something similar to what you're asking for.
Consider Timwi's answer first. But as a second option, you could do this, making it more like the C CONST keyword.
Reference-type (object) parameters are IN parameters by default. But because they are references, their method side effects and property accesses are done to the object outside the method. The object doesn't have to be passed out. It has still been modified by the method.
However, a value-type (struct) parameter is also IN by default, and cannot have side effects or property modifications on the element that was passed in. Instead, it gets COPIED ON WRITE before going into the method. Any changes to it inside that method die when the method goes out of scope (the end of the method).
Do NOT change your classes to structs just to accommodate this need. It's a bad idea. But if they should be structs anyway, now you'll know.
BTW, half the programming community doesn't properly understand this concept but thinks they do (indeed, I've found inaccuracies on the matter of parameter direction in C# in several books). If you want to comment on the accuracy of my statements, please double check to make sure you know what you're talking about.

How can I access the backing variable of an auto-implemented property?

In the past we declared properties like this:
public class MyClass
{
private int _age;
public int Age
{
get{ return _age; }
set{ _age = value; }
}
}
Now we can do:
public class MyClass
{
public int Age {get; set;}
}
My question is, how can I access the private variable that is created automatically using this notation?
I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?
The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set.
If you want to access the private member that these properties use, that's usually for a few reasons:
You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly.
You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.
public class MyClass
{
public int Age {get; private set;}
}
This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.
Your usage of automatic properties implies that you do not need any getting/setting logic for the property thus a private backing variable is unneccessary.
Don't use automatic properties if you have any complex logic in your class. Just go private int _age and normal getters/setters as you normally would.
IMO, automatic properties are more suited for quickly implementing throwaway objects or temporary data capsules like:
public class TempMessage {
public int FromID { get; set; }
public int ToID { get; set; }
public string Message { get; set; }
}
Where you don't need much logic.
This syntax is commonly called "syntax sugar", which means that the compiler takes that syntax and translates it into something else. In your example, the compiler would generate code that looks something like this:
[CompilerGenerated]
private int <Age>k_BackingField;
public int Age
{
[CompilerGenerated]
get
{
return this.<Age>k_BackingField;
}
[CompilerGenerated]
set
{
this.<Age>k_BackingField = value;
}
Even knowing all of that, you could probably access the backing field directly but that sort of defeats the purpose of using automatic properties. I say probably here because you then depend on an implementation detail that could change at any point in a future release of the C# compiler.
Behind the scenes what happens is the injection of a private member variable, prefixed with <>k__AutomaticallyGeneratedPropertyField#
From C# 3.0 Automatic Properties explained
Although it may be possible to use that private member directly, it's very hacky and unnecessary.
You shouldn't, and it's very unlikely you need to. If you need to access the property, just use the public property (e.g. this.Age). There's nothing special about the private field backing the public property, using it in preference to the property is just superstition.
You can't, it's a language feature as opposed to a IDE feature. To be honest i'd prefer then IDE to add the private variable in for you. I agree that it is slightly weird for the class to internally have to use the public entry point to access its own variables. Hence I don't use this new feature that much myself.

Categories