Declare multiple public variables with same property - c#

public String name
{
get;
set;
}
public String email
{
get;
set;
}
public String address
{
get;
set;
}
Is there an easier way to declare multiple variables with same property under one accessibility like this?
Something like
public String name, email, address
{
get;
set;
}

You could package them together in a separate class and then use that as a property:
class Info
{
public String name { get; set; }
public String email { get; set; }
public String address { get; set; }
}
class Person
{
public Info info { get; set; }
}
Obviously it's not what you're after in terms of inlining, but it does present a cleaner option if Info is something you'd use in more than one place. If you're not going to use that class anywhere else, then it's pointless.
Note, as an aside, that I'm using your conventions for capitalization of properties, but it's a "convention" to use Pascal case.

If you don't care for OOP and just want a bunch of strings collected in one variable you can do this with a simple Tuple in your case. It would look like this.
var bunchOfStrings = new Tuple<String,String,String>(String.Empty,String.Empty,String.Empty);
Console.Writeline("{0},{1},{2}",bunchOfStrings.Item1
,bunchOfStrings.Item2
,bunchOfStrings.Item3);
But keep in mind, you hide information with this approach. The items are just numbered and you loose any connection to the semantic of the items.

Related

Returning different versions of set of data

So I have a class with a static method that uses EF to retrieve certain set of mailing lists and maps to the class.
public static List<MailingList> GetMailingListsForUser(IUsersAccess user, IProspectorDataSource db )
{
return db.MailingLists.Where(x => x.UserID == user.UserID).ToList()
.Select(y => new MailingList(y, db) ).ToList();
}
Now though I have a proc that will return the MailingList plus some extra stuff. I don't want to add these extra columns (which will be used in other sections and areas of functionality) to this class. What is the best way to address this?
I am thinking a Factory Pattern that will generate a different class that implements different contracts (interfaces) based on whats needed. Going to try implement it and will post code/working when completed.
Was wondering what other people have done in instances like this and if there are any better ways to address this.
Edit: (some extra information to help people understand what I mean).
public class MailingList
{
public int MailingListID { get; set; }
public string Name { get; set; }
public string Comments { get; set; }
public List<string> Tags { get; set; }
public int UserID { get; set; }
public System.DateTime DateCreated { get; set; }
public string CreatedBy { get; set; }
public System.DateTime LastModified { get; set; }
public string ModifiedBy { get; set; }
public List<MailingListAddress> MailingListAddresses { get; set; }
That is the definition of an object that we return. Now there is a new instance where I am going to return some extra columns from a proc and map to MailingList. So I could just add the properties to here but the issue is MailingListAddresses will be null as they will not be returned by the stored proc. So is there a way to map to specific properties and not have to return null for MailingListAddresses to the front end every time.
This was fixed by a senior developer who ended up going with the factory pattern. I will add the code when I get back to work :)

Resharper: Don't change order of member variables in JSON classes

The order of the members can be set up in the ReSharper options in Languages, C#, Type Members Layout. Resharper is doing it correctly. However, I would like to exclude certain classes which contain JSONProperty attribute.
So for example, refer class below. I don't want Resharper to reorder the members in it.
internal class ExecutionParametersJson
{
[JsonProperty("Factor")]
public string Factor { get; set; }
[JsonProperty("Penalty")]
public string Penalty { get; set; }
[JsonProperty("Origin")]
public string Origin { get; set; }
[JsonProperty("InterFactor")]
public string InterFactor { get; set; }
}
I am using latest version of Resharper.
Can anyone show me how to configure Resharper to achieve this?
Actually, I tried putting Order attribute in it. But that didn't do any difference.
[JsonProperty("Factor", Order = 1)]
public string Factor{ get; set; }
However, I would like to exclude certain classes which contain JSONProperty attribute.
Yes that can be done rather easily.
Given this exammple code, note the additional properties I included purely to prove a later point:
internal class ExecutionParametersJson
{
[JsonProperty("Factor")]
public string Factor { get; set; }
public string SomeProperty { get; set; }
[JsonProperty("Penalty")]
public string Penalty { get; set; }
[JsonProperty("Origin")]
public string Origin { get; set; }
public int SomeOtherProperty { get; set; }
[JsonProperty("InterFactor")]
public string InterFactor { get; set; }
}
...then choose Resharper.Options.Code Editing.c#.File Layout, the list of patterns appears:
Choose your preferred pattern. Here I chose Default Pattern. I've been adding to it in the past so it may look different.
Scroll down till you find a region for Properties, you may have to create it like so:
Select Properties, Indexers, ensure Sort By is set to Name.
Double-click Properties, Indexers. The conditions editor appears. Add a top-level And condition; Not and specify the JsonProperty.
Now run Resharper.Edit.Cleanup Code on the file in question. All properties, except those with a JsonProperty attribute, will be sorted alphabetically and placed into a region titled Properties.
internal class ExecutionParametersJson
{
#region Properties
public int SomeOtherProperty { get; set; }
public string SomeProperty { get; set; }
#endregion
[JsonProperty("Factor")]
public string Factor { get; set; }
[JsonProperty("Penalty")]
public string Penalty { get; set; }
[JsonProperty("Origin")]
public string Origin { get; set; }
[JsonProperty("InterFactor")]
public string InterFactor { get; set; }
}
Now the additional properties I included here was just to prove how you format members conditionally. Feel free to remove these properties; the #region or customise to your liking.
Moving on
You may want to tidy this up a bit and create a specific pattern in Resharper called JSON Classes or some such.

Group Properties within partial class

I have 5 Properties within my class that are all very similar; I want to group them. The class they are contained in used to look like this:
class Car
{
public string PropA { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
public Car() { }
}
So with Intellisense, I would be presented with:
Car car = new Car();
car.PropA
.PropB
.PropC
..I would be presented with the 3 properties. What I want is for it to be contained within it's own little group, so I would have to do:
car.Props.PropA = "example";
I created a partial class to hide them in, but I am not sure if this is the correct way to do it:
class Car
{
public Props { get; set; }
public Car() { }
}
partial class Props
{
public string PropA { get; set; }
public string PropB { get; set; }
public string PropC { get; set; }
}
Is there a better way to go about this? I ask because I am creating a class library and usability is very important.
The partial keyword is used to split a class's implementation among multiple files. Knowing that, it doesn't help (or hurt) in this situation.
Without knowing more about your design, your solution seems reasonable. Just get rid of the partial keyword, it's not appropriate here.
Agreed with what Patrick said. I had a question about your public setters though, and this is something I've been curious about how to handle myself.
if you're hoping for other people to use thing class (and assuming this wasn't just a mocked up example) are you sure you want people to just be able to willy nilly be able to set properties in your classes without going through a method/function that validates and/or handles the setting of the property?
this can be done like:
public class Props
{
public string PropA { get; private set; }
public string PropB { get; private set; }
public string PropC { get; private set; }
}
public Props() { }
public SetProps(string propA, string propB, string propC)
{
this.PropA = propA;
this.PropB = propB;
this.PropC = propC;
}
Now obviously doing something like this would depend on the nature of the requirements around the props (and this is an extremely simple example - all props have to be set at the same time). But with public setters a user of the class would not necessarily know the nature of the requirements, and the public setters could potentially allow them a way around how it was intended the class be used.

Using a KeyValuePair<> as Property vs. Separate Class vs. something else

What is the proper way to show "Admin Tables" in my "Business Objects"? I have the following on my Address object.
public class Address
{
public int AddressID { get; set; }
public KeyValuePair<short, string> County { get; set; }
...
}
Now how would I instantiate this object, as far as the KeyValuePair<,> properties go?
My guess is:
var myAddress = new Address { AddressID = 3, County = new KeyValuePair<short, string>(32, "La Crosse")}
EDIT
This is what I am replacing with the KeyValuePair<> on the recommendations of another Programmer.
.....Address.cs.....
public County County { get; set; }
.....County.cs.....
public class County
{
public short? CountyID { get; set; }
public string CountyName { get; set; }
}
Is there a better way between the two or a third way that is even better?
KeyValuePair<T1, T2> buys you nothing in this case.
Why not just be explicit?
public class Address
{
public int AddressID { get; set; }
public int CountyCode { get; set; }
public string CountyName { get; set; }
}
or another version would be that you define a type County with the two properties, then have a property of that type instead.
In code, clarity is king.
I just ran your code, and it worked as expected.
The country property has correct value Key = 32 and Value = La Crosse.
Your new code is ugly. I'd either remove the setter of the Country property, or make the Country class immutable. This kind of double mutability, is a bug waiting to happen.
Making the Country class immutable, is probably the right decision, since the Id=>Name mapping is fixed.
I'd use:
public class County
{
public short? ID { get; private set; }
public string Name { get; private set; }
private Country(short? id,string name)
{
ID=id;
Name=name;
}
}
Lukazoid gives a good hint why not to do this, bus in fact, the Initialization you are showing would work well. You could have proofen this rather easy using your Debugger. What is the question?
Create a Country object so it is clear what that short and string are supposed to represent.

How to avoid using the same identifier for Class Names and Property Names?

Here are a few example of classes and properties sharing the same identifier:
public Coordinates Coordinates { get; set; }
public Country Country { get; set; }
public Article Article { get; set; }
public Color Color { get; set; }
public Address Address { get; set; }
public Category Category { get; set; }
This problem occurs more frequently when using POCO with the Entity Framework as the Entity Framework uses the Property Name for the Relationships.
So what to do? Use non-standard class names?
public ClsCoordinates Coordinates { get; set; }
public ClsCountry Country { get; set; }
public ClsArticle Article { get; set; }
public ClsColor Color { get; set; }
public ClsAddress Address { get; set; }
public ClsCategory Category { get; set; }
Yuk
Or use more descriptive Property Names?
public Coordinates GeographicCoordinates { get; set; }
public Country GeographicCountry { get; set; }
public Article WebArticle { get; set; }
public Color BackgroundColor { get; set; }
public Address HomeAddress { get; set; }
public Category ProductCategory { get; set; }
Less than ideal, but can live with it I suppose.
Or JUST LIVE WITH IT?
What are you best practices?
This is sometimes known as the "Color Color" problem - and my advice is just to live with it.
The C# language specification has been designed for this not to be an issue. From section 7.5.4.1 of the C# 3 spec:
In a member access of the form E.I, if
E is a single identifier, and if the
meaning of E as a simple-name (§7.5.2)
is a constant, field, property, local
variable, or parameter with the same
type as the meaning of E as a
type-name (§3.8), then both possible
meanings of E are permitted. The two
possible meanings of E.I are never
ambiguous, since I must necessarily be
a member of the type E in both cases.
In other words, the rule simply
permits access to the static members
and nested types of E where a
compile-time error would otherwise
have occurred.
(Followed by an example.)
Obviously when you can provide a more descriptive property name, that's great - but quite often the best name really is the same as the property.
This occurs in the framework itself - for example, HttpWebRequest.CookieContainer is of type CookieContainer, and there are various types with an Evidence property of type Evidence.
I try to rather use more descriptive property names.
Changing the class name feels like it is defeating the purpose, as where most developers tend to under emphisise the use of good and descriptive Variable/Property names.
As in your example, for instance an Address acan be
public Address HomeAddress { get; set; }
public Address PostalAddress { get; set; }
public Address CompanyAddress { get; set; }
etc. You can see where im going with this.
I personally am not shy about having the class name and the property name match if the names are truly applicable. For example, on an Address class, having a property called Country which is typed as a class named Country makes sense and there really isn't any name for the property that isn't redundant. I try to avoid collisions using descriptive property names, but sometimes the name for the property and its type are the best names to use and using anything else diminishes clarity rather than improves it.
I would strongly recommend against a Hungarian-like prefix on classes. That is just plain fugly.
I think the name of a property should just decribe what it is. When it is an Apple, just name it an Apple.
Why would anyone, just for property readability, use hungarians at class names. It decreases class name readability.
When accessing the Property, you can use the This keyword for preventing yourself to accidently misreading the the property as a class:
class Food
{
public Apple Apple
{
get;
set;
}
public void DoIt()
{
this.Apple = new Apple();
}
}
class Apple
{
}
See SA1101 of StyleCop "Verifies that calls to local members are prefixed with the 'this.' notation."

Categories