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 6 years ago.
Improve this question
I currently have this source of code as an example:
class Person
{
public Person create(string _name, int _uid)
{
return new Person()
{
name = _name,
uid = _uid,
};
}
public int uid;
public string name;
}
I know it isn't the biggest of deals but I work on projects that have multiple developers meaning conventions are important.
On the official .NET naming conventions documentation, it states do-not use symbols however, this method is for the use of adding to a List<Person> People = new List<Person>(); and is called like so:
People.Add(Person.create("Example", 1));
I have looked at sources like:
C# Property Examples
Which they use a prefix _ to declare its only temp to get or set a value which I then copied.
My question is, does this follow the .NET naming conventions or how can I keep it similar to the property names that currently exist?
The convention is to use camelCase for parameter names, so they should be named name and uid. It doesn't matter whether they're temporary, or long-lived, whether you use them and discard them or store them in a field.
While on the subject of naming conventions, methods should be named using PascalCase, so I would rename create to Create.
Your public fields should actually be properties (see Jon Skeet's Why Properties Matter for a complete explanation why), and should also be named using PascalCase.
public int Uid { get; private set; }
public string Name { get; private set; }
Finally, I'd question why the Person class has a non-static method to create an instance of Person. joe.Create("mike", 123) doesn't make much sense to me.
MSDN has a nice list of naming conventions here.
The only thing it's missing is using a leading underscore + snakeCase for private fields (e.g. _myAge). This is not endorsed by Microsoft, although it's a widely used convention. It's also encouraged by some refactoring tools such as ReSharper.
Take a look at the readonly keyword
IMHO prefix "_" for any variables is not common for c#
code source https://msdn.microsoft.com/de-de/library/acdd6hb7.aspx
public class ReadOnlyTest
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
static void Main()
{
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
p2.x = 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}
/*
Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
*/
Related
This question already has answers here:
Enum "Inheritance"
(17 answers)
Closed 2 years ago.
I recently started using enums for commonly used names in my application. The issue is that enums cannot be inherited. This is the intent:
public enum foreignCars
{
Mazda = 0,
Nissan = 1,
Peugot = 2
}
public enum allCars : foreignCars
{
BMW = 3,
VW = 4,
Audi = 5
}
Of course, this can't be done. In similar questions I found, people have suggested using classes for this instead, like:
public static class foreignCars
{
int Mazda = 0;
int Nissan = 1;
int Peugot = 2;
}
public static class allCars : foreignCars
{
int BMW = 3;
int VW = 4;
int Audi = 5;
}
But static classes can't be inherited either! So I would have to make them non-static and create objects just to be able to reference these names in my application, which defeats the whole purpose.
With that in mind, what is the best way to achieve what I want - having inheritable enum-like entities (so that I don't have to repeat car brands in both enums/classes/whatever), and without having to instantiate objects either? What is the proper approach here? This is the part that I couldn't find in any other questions, but if I missed something, please let me know.
EDIT: I would like to point out that I have reviewed similar questions asking about enum and static class inheritance, and I am fully aware that is not possible in C#. Therefore, I am looking for an alternative, which was not covered in these similar questions.
Enums in C# are a pretty weak implementation. They're basically just named values. Java's enums are a little nicer as they're actually classes with special semantics, so you could implement something similar to Java's enums...
public sealed class Car
{
public static readonly Mazda = new Car(0, "Mazda", true);
public static readonly Nissan = new Car(1, "Nissan", true);
public static readonly Peugeot = new Car(2, "Peugeot", true);
public static readonly BMW = new Car(3, "BMW", false);
public static readonly VW = new Car(4, "VW", false);
public static readonly Audi = new Car(5, "Audi", false);
private Car(int value, string name, bool isForeign)
{
Value = value;
Name = name;
IsForeign = isForeign;
}
public int Value { get; }
public string Name { get; }
public bool IsForeign { get; }
// TODO : Implement Equals and GetHashCode...
public override string ToString() => Name;
}
Notice that the only instances of Car that can be created here are declared within the class itself, and no instances can be constructed externally because the constructor is private. This behaves much like an enum in Java, and allows you to include additional fields to the enum, rather than just name and value.
One more thing to note here... IsForeign is declared as a bool. Foreign to you, might not be foreign to me, so consider globalization and localization too. Maybe you should specify Car by CountryOfManufacture or better still, something from .NET's Culture namespace.
If you're wondering where I got the inspiration for enum classes...Jimmy Bogard, the author of Automapper.
https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/
The general problem you're having is that you're attaching additional meaning to an enum. Once you do that it's no longer an enum it's a concept within your system which is usually something represented by an object.
Without knowing more about what you're doing it's hard to offer much more than work arounds. But the point is that "extra" information you want to attach, doesn't belong in the enum. It needs to be located somewhere else. I'll offer a simple example that leaves a lot to be desired but at least represents the concept outside the enum:
public enum allCars : int
{
// note in general this is a bad idea, you've
// created compile time construct to hold
// something that can change.
Mazda = 0,
Nissan = 1,
Peugot = 2,
BMW = 3,
VW = 4,
Audi = 5
}
public class Car
{
static HashSet<allCars> foreignCars = new HashSet<allCars>(
new allCars[] { allCars.Mazda, allCars.Nissan, allCars.Peugot });
public Car(allCars id)
{
this.CarId = id;
}
public allCars CarId { get; }
public bool IsForeignCar => foreignCars.Contains(this.CarId);
}
I've moved that idea of "is it a foreignCar" into the Car class itself which is probably dicey but it illustrates the general point. Having things set at compile time that can change - the enum itself and the pool of foreign cars - is usually not great. You'll probably want to refactor that out of the design as well.
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 5 years ago.
Improve this question
Is there a way to write this so I don't have to explicitly declare the field _D?
How do I get around the = new List<T>() when the class is implemented?
What I have:
class c {
private List<T> _D = new List<T>();
public List<T> D { get { return _D; } set { _D = value; } }
}
What I want:
class c {
public List<T> D { get; set; }
}
Wouldn't it be better to declare a constructor to assign the property a List<T>? As in:
class c {
c() { D = new List<t>(); }
public List<t> D { get; set; }
}
What are today's best practices when implementing properties and assigning initial values?
All three are technically correct. I found the first in a bit of code I'm taking over. I can't find any purpose behind the original code that declares all the property backing fields. I thought declaring backing fields was not a best practice since c# v3 .. except when you are actually going to use the private field somewhere in the class's methods, which isn't happening here.
You could look at assigning the initial List<> to the property as 'Using the property somewhere in the class.'
Or you could look at it as 'Pointless, do it like my third example instead.'
Which is generally regarded as best practice these days?
Since C# 6 you can do it this way:
public IList<int> Prop1 { get; set; } = new List<int> { 1, 2, 3 };
There are a few ways to achieve the same thing in .NET as well as best practices and recommendations. It all depends on your requirements and responsibilities for the object and properties. I saw a comment with a link to the programming guide which is excellent. These are just a few more examples.
public class C<T>
{
public List<T> D { get; set; } = new List<T>();
}
public class C2
{
public IReadOnlyList<int> D { get; private set; }
public C2()
{
D = new List<int>();
}
}
public class C3
{
private List<int> _d = null;
public List<int> D
{
get
{
return _d ?? new List<int>();
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm looking for a differences between declarations to define an integer numbers and declarations for a fields.
EXAMPLE: Declaration 'int b;' can be declaration for the inetger number b or it can be the declaration for the private field b. As it looks like, it depends on where this declaration is situated.
I know, that typical declaration to define a field is 'private string field;'
In the code below in the class MyClass I can't declare the integer numbers, but just the fields. Why?
I wrote 'int b;' because I wanted to declare the integer number b, but I got the field b. Visual Studio shows me, that 'b' is the field.
using System;
class MyClass
{
int b;
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.ReadLine();
}
}
All fields are variables, but not all variables are fields.
From the documentation,
A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type.
Or, more simply, fields are variables that are associated only with the class or object itself, not with a specific method.
Thus, when you have int b = 7;, it is technically correct to call it a variable, but it's more specific to call it a field. It's the same way that it's technically correct to simply call a Porsche Boxter a car - it is, in fact, a car, but it's more descriptive (and, therefore, potentially more useful) to call it a Boxter.
Note in particular that the definition of a field says absolutely nothing about what else is included in the class. A field is a field regardless of what other content you do (or don't) have in the class (so, for example, the fact that MyClass doesn't have a Main method is completely irrelevant).
Fields can be distinguished from a local variable, which is declared inside a method and is associated only with that particular method. For example:
public class MyClass {
public int a = 10; // This is a field
int b = 20; // Also a field
public void MyMethod() {
int c = 30; // This is a local variable, NOT a field
}
}
Note, in particular, that c is not "declared directly in a class or struct" - it's declared inside a method. Thus, by definition it's not a field.
Based on the wording in your question, I feel that your understanding of using the words "variables" and "field" is misguided.
You seem to be calling:
"variables" as private fields
"fields" as public fields
Take a look at the below code block, to help:
class MyClass
{
int b = 7; // this is a private field
private int c = 8; // this is a private field
public int d = 10; // this is a public field
}
In addition, from the code above, you can now understand the reason why you are unable to access b. It is due to the private access modifier that is assumed. You need to change it to a public field.
So, what you'll want to get your code up and going quickly is change:
int b = 7;
to
public int b = 7;
and then you can change
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.ReadLine();
}
to
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
MyClass mc = new MyClass(25);
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y, MyClass.z);
Console.WriteLine("{0}", mc.b);
Console.ReadLine();
}
Take special note that public fields should usually be avoided in favor for properties, you can read more about that by doing a few searches online.
Additional Resources
Fields (C# Programming Guide)
static (C# Reference)
Static Classes and Static Class Members (C# Programming Guide)
Properties (C# Programming Guide)
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 7 years ago.
Improve this question
I have a class and constructor in order to initiate it like this:
public class Merchant
{
public int userID;
public int clubID;
public short categoryID;
public string posTerminalID;
public string name;
public double score;
public double subClubSharePercent;
public double simClubSharePercent;
public bool isActive;
public string modificationDatetime;
public Merchant()
{
}
public Merchant(int uID, int cID, Int16 aID, string pID, string n, double s, double sSp, double sCp, Boolean iA, DateTime dt)
{
Date da = new Date();
this.userID = uID;
this.clubID = cID;
this.categoryID = aID;
this.posTerminalID = pID;
this.name = n;
this.score = s;
this.subClubSharePercent = sSp;
this.simClubSharePercent = sCp;
this.isActive = iA;
this.modificationDatetime = da;
}
}
how can i modify the class members value:
Use the constructor method again?
Create modify class and call it?
what is the differences between initializing class with constructor and syntax?
thank you.
Dan Field has definitely given you an adequate answer, but I figured I'd chime in with a few tidbits as well.
Constructors are useful for setting variables that otherwise could never be set by the developer. These include private fields, private functions, and private properties.
You've declared many public fields. You know they're fields because there is no 'setter' or 'getter' function. Properties, however, are defined by having the getter and setter functions. Setters and getters are not just a C# phenomenon, they're useful in many object-oriented languages.
In C#, public properties can be set by the programmer whenever necessary - initializing public properties through the constructor (with a few exceptions) isn't necessarily useful. That said, there are patterns where requiring every field to be passed into the constructor means that the object can't exist without all of its info. In your case, that's not apparently a concern as you have a parameterless constructor in public Merchant().
C# also allows for object initialization right in its syntax, without the need to pass in every property through parameters in the constructor.
Consider the difference here:
//Constructor with all parameters
public Merchant(int uID, int cID, Int16 aID, string pID, string n, double s, double sSp,
double sCp, Boolean iA, DateTime dt) {
Date da = new Date();
this.userID = uID;
this.clubID = cID;
this.categoryID = aID;
this.posTerminalID = pID;
this.name = n;
this.score = s;
this.subClubSharePercent = sSp;
this.simClubSharePercent = sCp;
this.isActive = iA;
this.modificationDatetime = da;
}
//Code using it
Merchant merchant = new Merchant(uID, cID, aID, pID, n, s, sSp, sCp, iA, dt);
versus
//Constructor with no parameters
public Merchant( ) { }
//Code using it
Merchant merchant = new Merchant( ) {
userID = uID,
categoryID = aID,
isActive = iA,
modificationDateTime = da
};
The main differences being that with the first method, you're enforcing all parameters to be present. The second method, however, gives the user more flexibility to instantiate only what they want/need.
You can only call a class constructor once. Once the object is constructed, it's constructed and that's just it (leaving aside any weird attempts to invoke the code in a constructor through reflection).
If you want to be able to use a single method to change the values of the class after it's been constructed, you'll have to write a method to do so (perhaps you don't want someone to change only one member variable at a time? running validations against the variables that, for thread-safety reasons, you wan tto run all at once?).
If you don't want outside objects to be able to modify the values of the class, you should probably make those public properties have a private set, e.g.:
public bool isActive { get; private set; }
This will make it clear that property can be read but not written outside the class itself, and prevent a non-member from modifying the variable.
If you want the properties to be settable only by a constructor (and not even a member method can change them), mark them readonly. But realize that to get new values here, you'll have to make a completely new object (i.e. new Merchant(param, param, param....).
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was thinking about language constructs and how when we talk about classes and objects in Object oriented languages we draw comparisons to real world. Like when people talk of Inheritance people would quote an example of Parent and Children. One thing that i don't find in OO languages that i know , mainly C, C++, C#, is that they don't have a mechanism to declare a property as mandatory. What i mean by that is I cannot define a class called human and say that face, hands and lets say eye are mandatory property of my class. By having that construct i can enforce that anyone who is using my class need to set those properties before using my class. If user forgets to set those properties then i should get an compile time error.
Just wanted to see community thoughts on that.
Here is reason why i had asked above question:
When i build my user controls, i want to make sure that users should set some of the properties in their code when they use my control. For example, lets say i build a customer user control that would be used by other developers in my team. Some of the properties that i have exposed are: "CustomerId", "FirstName", "LastName", "Address1", "City", "State" and ZipCode. Now i want to make sure that any consumer of my control should set "CustomerId". Using Constructor to enforce that the value is set is a way but it will throw a run time exception plus how would user call that constructor from .cs file without dynamically creating the control and adding it to control collection.
You can do that, with a DDD principle: create a class with a private default constructor, and a public constructor that accept required parameters and validate its values. If a value is invalid, throw an exception so that the object cannot be created. Properties could also have private setters instead of public setters.
You can also create a 'Mandatory' attribute and put those on top of the properties that are mandatory; and have a mechanism that checks this based on whether a property has been decorated with the attribute or not.
Example:
public class BlogEntry
{
private BlogEntry() {}
public BlogEntry(string title, string body)
{
LastModifiedDate = DateTime.Now;
Title = title;
Body = body;
var blogEntryValidator = new BlogEntryValidator();
blogEntryValidator.ValidateAndThrow(this);
}
public int Id { get; private set; }
public string Title { get; private set; }
public string Body { get; private set; }
public DateTime? LastPublishDate { get; private set; }
public DateTime LastModifiedDate { get; private set; }
public virtual ICollection<Comment> Comments { get; private set; }
public void Publish()
{
LastPublishDate = DateTime.Now;
}
public void Unpublish()
{
LastPublishDate = null;
}
public void Modify(string title, string body)
{
Title = title;
Body = body;
LastModifiedDate = DateTime.Now;
}
public Comment AddComment(string commentText, string emailAddress, string name)
{
var comment = new Comment(this, commentText, emailAddress, name);
if (Comments == null) Comments = new List<Comment>();
Comments.Add(comment);
return comment;
}
public void RemoveComment(Comment comment)
{
Comments.Remove(comment);
}
}
public class Comment
{
private Comment() {}
public Comment(BlogEntry blogEntry, string name, string emailAddress, string commentText)
{
BlogEntry = blogEntry;
Name = name;
EmailAddress = emailAddress;
CommentText = commentText;
DateWritten = DateTime.Now;
var commentValidator = new CommentValidator();
commentValidator.ValidateAndThrow(this);
}
public int Id { get; private set; }
public string Name { get; private set; }
public string EmailAddress { get; private set; }
public string CommentText { get; private set; }
public DateTime DateWritten { get; private set; }
public BlogEntry BlogEntry { get; private set; }
}
Yes, C++ and C# allow for this via constructors.
class A
{
public:
A(int x, int y, int z)
: _x(x_, _y(y), _z(z) {}
private:
int _x;
int _y;
int _z;
};
You cannot create an instance of A without providing values for _x, _y, and _z.
The reason is that state needed to fulfil class invariants should be provided during object construction, so you should provide values of 'mandatory' properties as constructor parameters. Your question is based on false assumption that an object is characterized by setting state with properties. This is wrong for a handful of reasons, some of which are:
many, if not most OO languages have no properties: Java, C++,...
what you use is only formally an object, it is actually a plain record and it is not very object oriented, same as e.g. C++ struct without methods (see notes at the bottom about setters vs methods)
Allowing the client to create instances of the objects which are only later set up with correct values for mandatory state is sure-fire way to spend many hours in company of debugger.
Let's take some User with invariant that first and last name must always be set.
class User {
public User(string first, string last) { ... }
public User(string first, string last, uint age) : this(first, last) { ... }
}
// client code:
var user = new User("john", "doe");
var user2 = new User("Clint", "Eastwood", 82);
Compiler ensures that no one can instantiate the object without fulfilling the invariants.
Now compare it with your approach:
class User {
public User(string first, string last) { ... }
public User(uint age) { ... }
[Mandatory] public string FirstName { get; set; }
[Mandatory] public string LastName { get; set; }
}
// client code:
var actor = new User(82); // << invalid
actor.FirstName = "Clint";
actor.LastName = "Eastwood"; // << valid
This approach results in more code and allows for a period of time (between << invalid and << valid) where your object is not in a valid state. What if some of property setters throw an exception? You are left with broken object instance floating around. Do you expect the compiler to also verify that code in the setter can not throw? Do you think it is even possible? Besides that, every client which instantiates User instances must check what are the mandatory properties and make sure to set all of them. This effectively breaks encapsulation.
IMO, property setters should be rare, unlike getters. I believe that in such a class you should not have setters for FirstName/LastName, only getters. Instead there should be a method SetName(string first, string last) if you really want to allow name changing. Here's why:
// lets rename actor
actor.FirstName = "John";
actor.LastName = "Wayne";
If the last line throws, you are left with John Eastwood, an actor I have never heard about. With actor.SetName("John", "Wayne") this can't happen.
Additionally, what about property which have dependency in order you specify them, e.g.
obj.ErrorCode = 123; // imagine that error code must be != 0
obj.ErrorMsg = "foo"; // in order to be allowed to set error code
Would you also introduce attributes for that instead of having obj.SetErrorInfo(123, "foo")? This makes it obvious that properties break encapsulation as the order is caused by the implementation detail, unlike with method call.
Quite often, in languages like C#, required state or dependencies is provided in constructor while optional state can be set through properties. However, it is not properties or inheritance which make a language object-oriented.
Sure you can! Just use parameters in constructor to denote which are mandatory.
public class Human
{
public Face Face { get; set; }
public Hand Hand { get; set; }
public Human(Face face, Hand hand) {} etc...
}
In this instance, you cannot use the private constructor, so these properties are essentially "mandatory" in order to use the Human class.