i'm learning C#.
ok, i have a problem:
i have a class :
class Couple{
private double first{private set; public get;}
private double second{private set; public get;}
}
first question: am i right, that these properities have public getter and private setter? (it's sounds strange, i know, but need to know difference between private/public field and private/public property with public/private set/get )
and second question.
if i want a class :
class AnyCouple{
public Type AnyCouple {public set; public get;}
private AnyCouple first{private set; public get;}
private AnyCouple second{private set; public get;}
}
how to make it?
dummy questions, i know, sorry
The class you want is Tuple.
As for the general principle, you want Generics.
Regarding properties, you can apply a different access modifier to one of the accessors, but not to both (the one to which you don't apply a modifier uses the modifier applied to the property itself). And the applied modifier must be more restrictive, not more relaxed:
private double first {private set; public get;} // wrong, 2 modifiers
private double first { set; public get;} // wrong, a relaxed modifier
public double first {get; private set;} // correct
A nice article on MSDN about that.
For your first question, yes, you are right. The properties first and second have a private setter and a public getter. However, as written, your code won't compile. If you specify an access modifier on a getter or setter it must be more restrictive than the access modifier for the property and you can't specify an access modifier on both properties. Additionally, note that in idiomatics C#, we write the getter first and setter second and we give properties PascalCase names like
public double First { get; private set; }
This will achieve a property named First with a public getter and a private setter and it is written idiomatically.
For your second question, you should use generics. You could do it all like this:
public class MyTuple<T1, T2> {
private readonly T1 first;
public T1 First { get { return this.first; } }
private readonly T2 second;
public T2 Second { get { return this.second; } }
public MyTuple(T1 first, T2 second) {
this.first = first;
this.second = second;
}
}
But, this is already built in to the .NET Framework. You can just use Tuple<T1, T2>. Note that its Item1 and Item2 properties (analogous to your first and second) have a public getter; it is backed by a private readonly field.
As for the first question, the private double first means that both the getter and setter will be private. Really you want public double first and then control the accessibility of the getter and setter as you have done. I believe that when the compiler sees this kind of property declaration, it creates code for the backing store (always a private field) and get/setters as you specifiy.
As mentioned by #GSerg, the Tuple class is what you want.
Related
For proper encapsulation, should I use a private property with a manual getter method like in Java:
public class Foo {
private int Prop { get; set; }
public Foo
{
Prop = 1;
}
public int GetProp()
{
return Prop;
}
}
Or should I simply use a public property?
public class Foo {
public int Prop { get; private set; }
public Foo
{
Prop = 1;
}
}
Properties are the way of creating getters and setters in C#, so there is no reason to create a getter method, like you would in Java.
In other words: You should use the second example.
Typically the proper way to do this is:
private int prop;
public int Prop
{
get { return prop; }
set { prop = value; } //do other stuff within set if needed.
}
This way you have access to everything, but can still do something custom (commonly NotifyPropertyChanged) if needed.
A property is just a syntactic sugar for get_PropertyName and set_PropertyName methods in c#.
public class Foo
{
public int Prop { get; private set; }
}
Is equivalent to:
public class Foo
{
private int _prop;
private void set_prop(int value) { _prop = value; }
public int get_prop() { return _prop; }
}
It's best that you use auto properties when possible and use properties with backing fields when you need to add logic to the getter/setter of individual fields.
If the property is going to be private, as it is in your first example, you should just use a field.
The point of a Property is usually that you have a get and set function, that can be used mostly like a variable. Your first example is really wierd - why not just make the getter only public? Readonly and Writeonly properties are not a uncommon sight:
//Public property with private get or writeonly
public int Prop { private get; set; }
//Readonyl property
public int Prop { get; private set; }
One important rule regarding the Backing field: It is very important that you do not mix up the Property and it's backing field, especially in class code. If you use Autoimplement Properties, that danger is non-existant. If your code is more complex than that, a common approach is to append a underscore (_) to the backing field name. Prop/prop is too easy to mix up. _Prop and Prop are really hard to mix up ,especialyl for autocompletion features.
In general, methods represent actions and properties represent data. While both your examples can be used identically, the 'proper' way of representing state is through properties, and using properties correctly tells consumers of your object that this is representing state, not an action.
You should also consider how things like serialization and intellisense are expecting properties instead of methods.
I tried to search for solutions, but my problem is I don't even know what terms to use. Generics, Delegates, LINQ, Reflection, and Abstract ideas could be part of the solution, but my "Google-fu" isn't turning up the right answer.
Question:
I have multiple classes (ClassA, ClassB, ClassC) that all have the same 2-3 properties DoThisA, DoThisB, DoThisC.
The way the code works is that I always want to do the same code to set DoThisA, DoThisB, and DoThisC when I process each of the classes.
For example, to simplify, the logic will always be:
{some computations to set string currentValueImProcessing to something}
if (xyz) [ClassA|B|C].DoThisA = currentValueImProcessing
else [ClassA|B|C].DoThisB = currentValueImProcessing
I don't want to write those same statements over and over, so how do I just send a reference to the class (A,B,C) to a method to do the logic?
If it was written correctly each of ClassA, ClassB, and ClassC would have implemented some generic class and I could use that, but I cannot. Each of the classes are independent but have the same named properties.
Any guidance on concepts/code?
Thanks!
Create an interface for your properties:
internal interface IDoThis
{
public string DoThisA { get; set; }
public string DoThisB { get; set; }
public string DoThisC { get; set; }
}
Then, make your classes implement it:
public class ClassA : IDoThis
{
public string DoThisA { get; set; }
public string DoThisB { get; set; }
public string DoThisC { get; set; }
}
public class ClassB : IDoThis
{
// Same properties
}
public class ClassC : IDoThis
{
// Same properties
}
This, way, you'll be able to create a static initializer method somewhere:
internal static class MyClassesExtensions
{
public static void InitTheStuff(this IDoThis obj)
{
// Do something here, for example:
if (String.IsNullOrEmpty(obj.DoThisA))
obj.DoThisA = "foo";
else
obj.DoThisB = obj.DoThisC;
}
}
And then you can just call this.InitTheStuff() anywhere from ClassA, ClassB and ClassC.
you can either use reflection or you can use dynamic (dynamic will use reflection for you)
dynamic obj = new ClassA();
obj.DoTHisA();
is how to do it with dynamic
I am assuming that you are talking about classes that you intend to instantiate. If DoThisA,B,C are static methods then you must use reflection
NOTE - if you can change the classes then add an interface as others have suggested, or even a common base class
The reflection one looks like this
var type = obj.GetType(); // obj is ClassX object
var method = type.GetMethod("DoTHisA");
method.Invoke(obj);
I have not checked this - so the syntax might be a bit off - but this is the basic mechanics of reflection method calling. YOu need to get fancier if there are multiple methods with the same name, if the methods takses params etc
There are at least four options open to you - maybe more.
Create an interface, which is implemented by all of your classes and that includes the common methods.
Create a base class from which all classes inherit. The common functionality can then be implemented in the base class. If the implementation differs depending on the clases, but you can define common signatures for the methods, make your base class an the common funtionality abstract. You then can implement the actual functionality in each of your classes.
Use a dynamic object as in #pm100's solution.
Use reflection to access the common functionality.
As a guidance methods 1. and 2. are to be preferred, as they allow your code to be checked on compile time. If, however, you do not have control over the classes that contain the common functionality - for example you do not have access to the source code or you are permitted to make changes to the code - you can use the other two methods.
If you'd ask me which of the two I would prefer, I guess that I would go for 3. over 4. But this is personal preference.
Prob you are talking about inheritance.
For your task you need a base abstract class with general properties:
public abstract class Base
{
public bool DoThisA { get; set; }
public bool DoThisB { get; set; }
}
and child classes:
public class A : Base { }
public class B : Base { }
public class C : Base { }
After that you can create a method which will accept object of type Base
public void Do(Base b, bool xyz, bool currentValueImProcessing)
{
if (xyz)
{
b.DoThisA = currentValueImProcessing;
}
else
{
b.DoThisB = currentValueImProcessing;
}
}
There are already many methods provided here, so just for the sake of completeness... Here's some runtime code generation:
public class ClassA
{
public string DoThisA { get; set; }
public int DoThisB { get; set; }
public bool DoThisC { get; set; }
public void Init()
{
// You can call this from anywhere, even from an unrelated class
MyClassInitializer<ClassA>.Init(this);
}
}
public static class MyClassInitializer<T>
{
// Create the getters/setters you need, and make sure they're static.
private static readonly Func<T, string> _getA = BuildGetter<string>("DoThisA");
private static readonly Action<T, string> _setA = BuildSetter<string>("DoThisA");
private static readonly Func<T, int> _getB = BuildGetter<int>("DoThisB");
private static readonly Action<T, int> _setB = BuildSetter<int>("DoThisB");
private static readonly Func<T, bool> _getC = BuildGetter<bool>("DoThisC");
private static readonly Action<T, bool> _setC = BuildSetter<bool>("DoThisC");
private static Func<T, TValue> BuildGetter<TValue>(string name)
{
var obj = Expression.Parameter(typeof(T));
return Expression.Lambda<Func<T, TValue>>(Expression.Property(obj, name), obj).Compile();
}
private static Action<T, TValue> BuildSetter<TValue>(string name)
{
var obj = Expression.Parameter(typeof(T));
var value = Expression.Parameter(typeof(TValue));
return Expression.Lambda<Action<T, TValue>>(Expression.Assign(Expression.Property(obj, name), value), obj, value).Compile();
}
public static void Init(T obj)
{
// Here's your custom initialization method
if (_getA(obj) == "Foo")
_setB(obj, 42);
else
_setC(obj, true);
}
}
Not necessarily the easiest one to grasp, but this should be much faster than using dynamic or reflection. That said, if you don't need the speed, stick with dynamic as it's easier.
is there any diffrence between this 3 auto properties ?
interface MyInterface {
public int p1 { get; set; }
public int p2 { get; }
public int p3 { set; }
}
also why we can write this code in an interface but not in a class ?
public int p { get; }
For the same reason you can write this in an interface:
interface IFace {
void Test();
}
Also, your interface is invalid, as public isn't valid in an interface. The point being, different things are legal in interfaces and classes.
When you do public int P1 { get; set; } in a class, that turns into a auto property. However, you can't do public int P1 { get; }, because what would you want that to mean? Should it always return 0? There is no way to set it. So if you want a read only property you have to define the getter yourself like this:
int _p1;
public int P1 {
get { return _p1; }
}
Also. Another way to achieve more or less the same is this:
public int P1 { get; private set; }
There are differences between those properties. Firstly, you should remove the public modifier from your declaration. Secondly, by putting get or set within the block you define what properties in derived classes should look like. For example, public int p1 { get; set; } requires getter and setter in a derived class, public int p2 { get; } only getter, and public int p3 { set; } requires only setter to be implemented.
You can't use access modifiers inside interfaces because interfaces are guidelines for other developers that force them to go in a certain direction when developing the implementing classes.
Look at this post for more information about that.
Keep in mind interface does NOT contain any implementation data. When you add property in an interface, it merely says that a class implementing this interface needs to have said property with get, set or both methods, depending on what you wrote. So any class implementing your interface has to implement (or have auto-generated) p1 property with get and set method, p2 with get method, and p3 with set method. Interface doesn't care whether these will be auto-generated or your own custom implementations, they just have to be in an implementing class.
Therefore, you can write
int p { get; }
in an interface as all it does is telling that any class implementing this interface has to have property p with getter, again, not caring about its actual implementation - you could write a getter that does some computations, returns some constant, etc. OTOH in a class writing the same would mean that you want a property with auto-generated backing field, except since it would have no setter, you couldn't actually change its value, so it would always have its default value 0.
And as noted, you cannot write access modifiers in an interface, as all interface members are implicitly public.
I have this code:
public string foo { get; set; }
Now, I interpret this as my object has a public property called foo, and both it's accessor's are public. If I write this:
private string foo { get; set; }
I interpret that as my object has a private property called foo, and both it's accessor's are private. I understand making the property itself private. What I don't understand is why the accessor's must be more restrictive? If I write:
private string foo { public get; public set; }
I interpret that my object has a private property called foo, and both's it's accessor's are public, which is the behavior that I want. I'd like the private property with public accessors. I mean, if I have to write a Get/Set method, I will. But I'm just confused as to why this is.
A property is actually (under water) nothing more than two methods:
public string foo { get; set; }
will translate into:
public string get_foo() { ... }
public void set_foo(string value) { ... }
These methods can only have ONE access modifier, not a combination of two.
If I remember correcly, C#v1 did not support access modifiers for the getters and setters. There was one access modifers for the property which was used for both functions.
In v2 it was possible to "override" one of getter/setter-pair, this way overrwriting the "other" function. There was no use to override both getters/setters, because in that would render the property-access modifier useless.
Why the access modifier for the getter/setter is more restrictive has, in my opinion, something to do with easier implementing interfaces which always have (implicitly public) properties.
For more info, read: http://msdn.microsoft.com/en-us/library/75e8y5dd(v=vs.80).aspx
Why you need such a property
private string foo { public get; public set; }
If you want to have you get set public, then make the property public.
The compiler will first check the access of the property and then its method. If the property is public then its method can have either public or private or any accessor
My textbook is referring to the this reference and it first implies that a property is somewhat static and does not store one with each object, but one for the entire class. Then later it says that a property is nonstatic. I am really confused. What is it?
Properties can be static or not static.
Static properties have the 'static' keyword, default is not static.
Properties that are static are stored for the entire class (there is only one).
Properties that are not static are stored per instance.
A property can be both static and non-static you decide which by using the static keyword.
public static int StaticProperty {get; set; }
public int InstanceProperty {get; set; }
On a side note, a property is actually two methods (or just one if you only implement the set or get).
public int MyProperty {get; set; }
is equivalent to
public void set_MyProperty(int value);
public int get_MyProperty();