Trying to do everything by the book, is this correct?:
public class JollyHockey
{
public string AnotherCoolProperty { get { return anotherCoolProperty; } }
string anotherCoolProperty;
public JollyHockey(string anotherCoolProperty)
{
this.anotherCoolProperty = anotherCoolProperty;
}
}
Or do some people use underscores for the private class variables?
Some people (including myself) prefix private class variables with an underscore (simply as a visual indication of what is being used where).
This is mainly a personal (or team) level style consideration and you can use what you want (or what your team has standardized on).
Just be sure you're consistent!
For what it's worth, you could also use auto-properties for your example:
public class JollyHockey
{
public string AnotherCoolProperty { get; private set; }
public JollyHockey(string anotherCoolProperty)
{
AnotherCoolProperty = anotherCoolProperty;
}
}
Or you can do this:
public class JollyHockey
{
public string AnotherCoolProperty { get; private set; }
public JollyHockey(string anotherCoolProperty)
{
this.AnotherCoolProperty = anotherCoolProperty;
}
}
I believe that your example agrees with the MS coding guidelines. However, I don't like it, and this is something that can be agreed upon by your team.
The reason I don't like it is because the underlying field name often conflicts with method parameters. I use an underscore to make it clear that they are private variables.
When a function parameter has the same name as a private field,
I usually prefix the parameter with an underscore
I think it makes sense
the ReSharper thing By fletcher is a good idea
Related
I know there are a few questions on stack overflow on this already but I haven't found any that answer my specific question. I came from a java development background and never bothered using the get; set; methods from C# until now.
I have the following code
class Test
{
public int test { get; set; }
}
In my main function I can declare a new Test and use t.Test = 5 and that works fine; however, when I switch the public to private I cannot access my get; and set; methods anymore... BUT when I use (Similar method to Java)
class Test
{
private int test;
public int getTest()
{
return this.test;
}
public void setTest(int test)
{
this.test = test;
}
}
I'm confused on the design philosophy. In C# should I no longer be using private variables (Only make it private if it's used internally in the class) and make them all public and use private get; private set; to control accessibility?
When you write this (I'm using different class and property names for clarity):
public class Test
{
public string Name { get; set; }
}
that's asking the compiler to create a private field with a public property. It's equivalent to:
public class Test
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
(Except the field name is autogenerated and not directly representable in C#.)
That's basically equivalent to what you'd write in Java as:
// Java
public class Test {
private String name;
public String getName() {
return name;
}
public String setName(String name) {
this.name = name;
}
}
... but clearly the C# is a lot more compact.
Basically, C#'s properties make for more readable code than having getter and setter methods as normal methods - but that's all they are, really. They're just used differently in code. The automatically implemented properties (as per the first snippet) make "trivial" properties simpler to express. In C# 6, you can write read-only automatically implemented properties too, which can be assigned to from the constructor but only the constructor.
Importantly though, you're still only making the properties part of the public API - not the fields. So if you later want to add some more logic (e.g. to have two properties derived from the same field, or something like that) you can do so without affecting either source or binary compatibility.
and make them all public and use
private get; private set; to control accessibility?
No, not really. Let's have a look at this scenario:
private int _a;
public int A
{
get { return _a; }
private set { _a = value; }
}
So this field _a is encapsulated and cannot be accesed from anywhere except the same class. But A is a public property and it is inside the class so it can access _a field and work with it however its set accessor is private, so it cannot be accessed from outside of the class...
But to do something like this usually makes little sense :
private int MyProperty { get; set; }
Ok, we created auto-implemented property to access private fields that it work with. But this property is private (used only inside the same class) and because it's auto-implemented it cannot contain any logic inside.
But if change it to :
public int MyProperty { get; private set; }
It's more useful and the main difference from first example is that it creates backing field automatically. Though it still impossible to add some logic but it encapsulates setter method and it's a way of creating read-only properties (at least read-only outside of class).
The other answer is true but I think it misses something important.
When you have:
class Test
{
public int test { get; set; }
}
There is an unseen, private variable in your class called something like _test. This is not accessible outside of the class and is accessed with get and set with set. For the most part, you won't change those methods, but the option is there for you in the future if you want to.
What you are using here are Auto-Implemented Properties.
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
In other words, the two code blocks you posted are functionally the same.
The part that might not be obvious is that you also can declare either the getter or setter private, not necessarily the whole property, i.e.
public int test { get; private set; }
which would make it possible to get the value, but impossible to set the value from outside the class.
However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties (C# Programming Guide).
Yes, you use private variables only when you need to scope things internally to your class. They're obviously not visible from the outside.
The main reason for using Properties as they are known is when you want to add logic to your gets or sets. Say you want to validate a value before assignment, or you may want to delay load values and cache them in a get etc.
Here is a typical example when you'd want to use a property, over a simple value field:
private float latitude;
public float Latitude {
get { return this.latitude; }
set {
if(value < -90 || value > 90)
{
throw new ArgumentOutOfRangeException("Invalid Latitude");
}
this.latitude = value;
}
}
Now you could quite easily make the property private too, but you'd still be able to embed logic in there, obviously just not access it from outside. A singleton pattern is an example that springs off the top of my head.
You can also make the setting private for a variable. This allows you more flexibility to prevent people updating something they shouldn't, yet still give them access to the variable if need be.
private float latitude;
public float Latitude {
get;
private set;
}
I've two Classes
public class DemoProperty
{
public int ID { get; set; }
public string Title { get; set; }
public string MenuCode { get; set; }
public string OriginalURL { get; set; }
}
public class MyCommonProperties
{
private static List<DemoProperty> _DemoList;
public static List<DemoProperty> DemoList
{
get { return _DemoList; }
set { _DemoList = value; }
}
}
My need is to keep some common data throughout the project.For that I've using an application variable and it holds a Dictionary<string,List<DemoProperty>>.
Global.asx
void Application_Start(object sender, EventArgs e)
{
Application["DemoProperty"] = new Dictionary<string,List<DemoProperty>>();
MyCommonProperties.DemoList= (Dictionary<string,List<DemoProperty>>)Application["CommonProperties"];
}
Actually I don't know more about its demerits. If it is a bad idea could you please suggest me a good one.
What the static keyword ensures, is that the specific property / class exists only once in your application.
If this is bad or not is a very general question to which the answer unfortunately seems to be "it depends". Ultimately it is a question how you want to design you program.
Making something static can however make automatic testing harder, because you can not easily decouple your program into smaller testable parts (as all parts directly interact with your static data). It also makes reading the code harder, because it could be hard to understand when and what modifies the global data.
I will try an example to underline this:
class Data {
public static string Entry;
}
class Operations {
void SetOne() {
Data.Entry = "one";
}
}
With this example, for someone calling SetOne() it might be non-obvious that the method actually sets something in Data.
Another approach could be:
class Data {
public string Entry;
}
class Operations {
void SetOne(Data data) {
data.Entry = "one";
}
}
Now for the caller its is more obvious that Data is used in some way by the method, because the call now looks like SetOne(data).
In my humble personal experience static was almost never a good idea. While it might make things quicker in the short run, its drawbacks concerning readability & testability of your code are usually too big to ignore.
Lets forgot about why I need this.
Can we create a class with name "class".
Below code resulted in compilation error as class is a reserve keyword.
public class class
{
}
so is there any hack or a way to fool C# compiler? :)
This Question was asked by interviewer in my last interview and he told me it is possible.
You could use:
public class #class
{
}
But why do you want that?
C# Keywords
Keywords are predefined, reserved identifiers that have special
meanings to the compiler. They cannot be used as identifiers in your
program unless they include # as a prefix. For example, #if is a valid
identifier but if is not because if is a keyword.
What i've learned from this answer was that new key-words won't be added globally but only as contextual key-words to avoid breaking programs written in earlier versions. You find a list in the link above.
So interestingly enough this is valid(better: compiling) code:
public class var
{
public void foo()
{
var var = new var();
}
}
Here's another one:
public class dynamic
{
public void foo()
{
dynamic dynamic = new dynamic();
}
}
But never do this. It will break your other code where you've used var or dynamic before.
Yet another alternative is through Unicode
using System;
public class Program
{
public static void Main()
{
cl\u0061ss a = new cl\u0061ss();
Console.WriteLine(a.GetType().Name);
}
}
public class cl\u0061ss
{
}
Note: Console.WriteLine() will print class
DotNetFiddle link is here.
Most programmers use underscore '_' at the beginning of the name of a variable or whatsoever if it is a reserved word e.g.
public class _class
{
}
variable declarations example
int _int;
Im starting a new project and i have some problem trying to implement some naming conventions.
I used to work with Classes starting with Uppercase and Singular, like Car or User, and my variables starting with lower case, so if I needed to declare a class that had some variables of type Car and User i would do it like this:
public Car car;
private User user;
Now im trying to use some properties and as i see they should also be PascalCase , wich mean if i need to declare the same examples i would be:
public Car Car { get; set; }
private User User { get; set; }
And you can all see what would the problem be here, or you don't see it as a problem?
So what should i do? what am i missing here?
The C# naming convention recommends everything that is public as well as classes, interfaces etc., to start with an uppercase letter. The rest should start lower case.
There is no problem with:
private User User { get; set; }
... since the position of each name (word) defines what is what.
The English language works the same way.
e.g.: "I love love." (pronoun, verb, noun)
What you're run into is called the Color Color problem, because the most common way it crops up is "I need a property called Color of a type called Color". C# has been specifically designed to manage Color Color situations elegantly.
For details, read section 7.6.4.1 "Identical simple names and type names" in the C# 4 specification.
The rules for Color Color situations are a bit complicated (believe me, they do not make the compiler implementer's life any easier!) and they can lead to some interesting corner cases. If this subject interests you then you should read my article on it:
http://blogs.msdn.com/b/ericlippert/archive/2009/07/06/color-color.aspx
I think in many cases the context means you'd have a specific name - e.g. Car customersCar, etc.
Saying that, many people don't have an issue with the name/type being the same - see this link:
Should a property have the same name as its type?
For naming conventions in general, following MS isn't a bad start -
http://msdn.microsoft.com/en-gb/library/vstudio/ms229045(v=vs.100).aspx
There is no issue here; As #NDJ suggested you can apply context to add additional prefix to the property if you do not feel comfortable; but this will not generally add additional meaning to the context.
As a general Microsoft style guide encourages the use of Pascal Case for properties.
For a more complete guide on capitalization see the following MSDN article
There is no problem there.
Because in the context where you would use the class it can not be misstaken for the property and vice versa.
Edit: Ok, Im going to assume you have the Userclass inside the carclass like this:
public class Car
{
private class User
{
}
private User User
{
get;
set;
}
}
Which indeed would create problems. Move out your user and the problem is solved.
public class Car
{
private User User
{
get;
set;
}
}
public class User
{
}
Barring the internal class problem that #Evelie pointed out you should not have any issue naming a property the same as the type - in fact this is not an uncommon practice. .NET has public Color Color properties all over the place.
As the following program illustrates the compiler can distinguich between instance calls and static calls:
void Main()
{
Car c = new Car();
c.Test();
}
public class Car
{
public Car()
{
User = new User();
}
public void Test()
{
User.Static(); // calls static method
User.Instance(); // implies this.User
}
public User User { get; set; }
}
// Define other methods and classes here
public class User
{
public static void Static()
{
Console.WriteLine("Static");
}
public void Instance()
{
Console.WriteLine("Instance");
}
}
I've seen a lot of example code written using something like (please forgive how horribly canned this is):
public class Test
{
public object Thingy { get; private set; }
}
Unfortunately, these kinds of examples never really explain why 'set' is set as private. So, I'm just wondering if there's a good, common example that will illustrate to me why something like this would be used.
I sort of see it - the property can be run to process some extra logic in addition to setting that field. I'm just confused on how it would be invoked, and why this approach would be used rather than a generic setter method.
This would be if you have a property that you don't want anyone to set but your class. This can be handy with database id's. The internal class can set it but you wouldn't want anyone else changing it. So you can give them read access but not write.
EDIT: One more point on this is that using what you showed there is helpful for automatic properties. Unfortunately with automatic properties you are unable to only specify get so to avoid exposing a setter publicly it is just made private.
EDIT: Just thought I would throw in an example. Automatic properties are great for clean, terse code. But like you showed there is a limitation in that you have to have get and set. So before it was like this for a property like you showed:
public class Test
{
private object thingy;
public object Thingy
{
get { return thingy; }
}
}
Now we can get rid of that unneeded private declaration but it requires both. So make private to get around that.
I know this was overkill on the explanation but different things kept popping in my head.
As a simple example; it is a cheap way of making an "immutable enough" object (for use in threading, state, etc). But also anywhere where the client simply shouldn't need to assign it, or can't be trusted to assign it (correctly).
Another example might be a list:
public List<Foo> Items {get;private set;}
since we might call obj.Items.Add() etc, but we would rarely assign obj.Items = .... However, this example is marred by needing explicit initialization in the constructor, and XmlSerializer hates it - to be honest for lists I mainly use:
private readonly List<Foo> items = new List<Foo>();
public List<Foo> Items {get { return items;}}
which solves both of these.
As another example, contrasting:
private readonly int foo;
public int Foo {get{return foo;}}
vs
private readonly int foo;
public int Foo {get{return foo;} private set {foo=value;}}
this pattern may be useful in serialization, for example with DataContractSerializer (with the addition of some attributes), since many serializers will still look for private accessors. This avoids us having to decorate our internal state (foo), but gives the veneer of privacy to the set.
Ultimately anything can be bypasses and assigned via reflection, so private set is only intended to avoid accidental damage to data.
The private makes it into a readonly property. A common example is if you have multiple classes passing around a single object, you don't want another class to be able to modify the instance.
Basically, it is a readonly property. If it was written in full (not as an auto property) you would simply leave out the setter.
Two examples that are largely the same:
class Foo1
{
public int Id { get; private set; }
public Foo1()
{
Id = lastId ++;
}
}
class Foo2
{
private int _id;
public int Id { get { return _id; } }
public Foo2()
{
_id = lastId ++;
}
}
I've seen this used with the design:
public class whatever
{
public string WhateverId { get; private set; }
public static whatever Create(string whateverId)
{
return new whatever() { WhateverId = whateverId };
}
}
So you create whatever class, but after it's created the id can't be changed because it might break things that are connected to it.
the private set just gives the simple initializer syntax, I kind of like it for some scenarios.
Also can be used if it's changeable, but you need to manage it when changes are made
public void SetWhateverId(string whateverId)
{
DisconnectAllCurrentWhateverIdReferences();
WhateverId = whateverId;
ReconnectAllPreviousWhateverIdReferences();
}
This syntax allows you to provide a public-facing property that appears read-only to consumers of your API but internally can be changing. By auto-implementing in this way, you avoid having to write boilerplate code such as a distinct setter or a backing field for the value, and you leave room in your design to add a bespoke set algorithm if it is deemed necessary at some point in the future without having to decide right away.
private set is very handy for simple immutable value types.
struct Point
{
public int X { get; private set; }
public int Y { get; private set; }
public Point(int x, int y)
{
this = default(Point);
X = x;
Y = y;
}
}
This is just laziness that comes about from auto-properties. Before auto properties were around, people would implement the getter and omit the setter for properties which are meant to be read-only.
public class Test
{
private /*readonly*/ Type _thingy;
public Type Thingy { get { return _thingy; } }
}
Hopefully, C# 5 will allow you to create auto-properties with a getter only - because that's what everyone wants. (They should make readonly setters in auto-props too, I need that badly)
To answer the question of a common scenario where this might be used...
In an MVP pattern, if your Model exposes some properties for your Presenter I would write
public string Bazinga { get; private set; }
Now, the Model can change this value but other classes that use it cannot.