So I'm trying to convert an entity into a DTO using the exact same type. Both types (classes) are the exact same except they are in different namespaces.
Should I need to cast them when I reference either one from the other namespace?
Or should VS automatically know and recognize they are the exact same although in different files?
Thanks
namespace SomeInternetShoppingSite
{
public class Client
{
public int Id { get; }
public sprint FirstName { get; }
...
}
}
namespace SomeOnlineBankingSite
{
public class Client
{
public int Id { get; }
public sprint FirstName { get; }
...
}
}
Do you really think the following should be legal?
var bankClient = new SomeOnlineBankingSite.Client(...);
var shoppingClient = (SomeInternetShoppingSite.Client)bankClient;
Allthough both classes are identical they are two completely different abstractions of two very distinct concepts. Even if the compiler can easily enough figure out that the type definitions are the same, it has no right to allow an explicit or implicit conversion between the two; only the authors of the classes have the right to allow that conversion if they so wish to, implementing a cast operator, a static factory method or what have you.
Basically what you're describing is duck typing. The closest C# equivalent is the "dynamic" keyword but I don't think that's exactly what you're asking for.
As others have pointed out, C# does not, in general, follow the typing model you've described and you probably wouldn't want it to. As InBetween's example shows, there's a big difference between "same name," "same interface," and "same meaning."
To answer the question more directly, first, I seriously question the wisdom of having two identical classes in separate namespaces - it seems like a pretty clear violation of the Don't Repeat Yourself principal. With that said, if define an implicit conversion between them that should allow you to use them more or less interchangeably (although the downside to that is it could get confusing which of the two objects you're referring to; I'm inclined to say that it's a bad practice based on that fact along).
Related
Or why is the following impossible:
class Material
{
class Keys
{
...
}
Material.Keys Keys { get; set; } // Illegal
}
I don't see any possible ambiguity. When accessed by instance, return the property. When access statically, return the class. Or am I missing something?
I'm not asking for a "fix" (I know I could just name it differently, like MaterialKeys or the like), but more of a technical reason behind this limit.
But imagine you had this:
class Material
{
class Keys
{
...
}
static Material.Keys Keys = new Keys();
}
Now both are at "static" scope. Now, can the compiler disambiguate in all cases? If not, then this can't be allowed.
I suppose it's possible that the disambiguation would work for static fields/properties/methods, and not for instance members. Or the other way around. If that were the case, would you want the language specification to allow an instance member to have the same name as an internal class, but disallow it for statics? That would just be confusing.
But then, having a member match the name of an internal class is pretty confusing anyway.
"Anything that's not ambiguous should be legal" is absolutely NOT a design principle of the C# language. The C# language is designed to be a "pit of quality" language; that is, the rules of the language should throw you into a pit full of clearly correct code, and you have to work to climb out of the pit to turn it into incorrect code. The idea that "whatever is not ambiguous should be legal" works in most cases directly against the concept of a "pit of quality" language.
Furthermore, your idea that I need to provide you a justification for not doing a feature is backwards. We don't ever need to provide justification for not doing a feature. Rather, proposed features must be justified by demonstrating that their benefits outweigh their enormous costs. Features are very expensive and we have a limited budget; we must only do the very best features to yield their benefits to our customers.
Your proposed feature enables the easy production of code that is brittle and confusing; it helps make C# into a "pit of despair" language instead of a "pit of quality" language. Features which add brittleness and confusion to the language must add an enormous benefit to compensate for those costs. What is in your opinion the enormous benefit that this feature adds to the language that justifies its costs?
If the answer is "there is no such benefit" then now you know why the language doesn't have that feature: because it makes the language worse, net.
If there is a benefit, I'm happy to consider its merits for hypothetical future versions of the language.
You said,
When accessed by instance, return the property. When access statically, return the class.
But what if you say just Keys somewhere inside Material? Is this a static or instance access? Does this refer to the property Keys or the nested type Keys? It is actually ambiguous.
For example,
class Material
{
class Keys
{
public static int Length;
}
string Keys { get; set; }
public void Process()
{
// Does this refer to string.Length (via property Keys)
// or Material.Keys.Length? It actually refers to both.
Console.WriteLine(Keys.Length);
}
}
As pointed out in the comments, this is not the whole story; but almost. It is valid to have a property named Color of the type Color and there is no clash:
public Color Color { get; set; }
Color.FromName(...) // refers to static method on the type ‘Color’
Color.ToString() // refers to instance method on the property’s value
But this is easy to resolve simply because things in the current scope win over things in more outer scopes:
public class MyType { public string FromName(string name) { return null; } }
public MyType Color;
Color.FromName(...) // unambiguously refers to MyType::FromName(string)
// via the property Color
Not so easy in your example — the nested class Keys and the property Keys are in the same scope (have the same declaring type). How do you decide which to give priority? And even if you did decide to give one of them priority, this would be only marginally useful because you could still only have two things of the same name, and one would have to be static and the other instance.
My answer approaches the question from a slightly different perspective, compared to the other questions. Of the following two statements in a C# language specification:
The same identifier may not be used in different definitions within one scope
and
The same identifier may not be used in different definitions within one scope, unless it is probably impossible for any ambiguity to arise when the identifier is used
, the first is much simpler.
Simplicity is a key goal in language design, because simpler languages are easier for compiler and interpreter authors to implement, easier for tools to generate and manipulate, easier for beginners to learn, and easier for programmers to understand. When considering any language feature, the complexity that that feature adds to the language should be considered as a negative, and must therefore be balanced by an at least equal measure of usefulness. As you stated yourself, allowing this would add no real functionality (as it is so easy to work around), so there was no compelling reason to further complicate the C# spec by including it.
Because the nested class Keys is a member of Material as is the property Keys. You've got two members called Keys.
In the same way you can't have two properties called the same thing:
public class Bar
{
private bool Foo { get; set; }
private string Foo { get; set; }
}
When you access Foo which one are you trying to access?
public class Material : Keys
{
private Keys K { get; set; }
}
public class Keys
{
}
Works fine, but is probably not what you're after.
I run into this frequently enough that I thought I'd see what others had to say about it.
Using the StyleCop conventions, I find that I often have a property name that is hard to make different than the class name it is accessing. For example:
public class ProjectManager
{
// Stuff here
}
public class OtherClass
{
private ProjectManager ProjectManager { get; set; }
}
It compiles and runs, but seems like it would be an easy way to confuse things, even with the use of "this".
This is actually a very common pattern in .Net programming. Particularly so with enum types and members as it's the .Net Design Guidelines recommended way of programming.
4.0 design guidelines reference
http://msdn.microsoft.com/en-us/library/ms229012(v=VS.100).aspx
While it may be a bit confusing, it's not once you've seen it a few times. The tools well support this pattern and given one is a type and the other an instance it's hard to accidentally invert them without causing a compilation error.
That is a typical naming convention when there will only be a single property of type ProjectManager within any given class. It ceases to be confusing because there are no other uses of the ProjectManager type.
Of course, if there are other uses, then you need different names.
I agree with the other answers. For completeness sake, sometimes I find a way to generalize the class name a bit more. I understand your example was just an example, but one way to do it would be:
public class Person
{
// Stuff here
}
public class OtherClass
{
private Person ProjectManager { get; set; }
}
This helps make it a bit more readable. But it is perfectly acceptable (and even encouraged) to have identical class name and property.
Since the standard c# convention is to capitalize the first letter of public properties, the old c++ convention of initial capital for type names, and initial lowercase for non-type names does not prevent the classic name collision where the most obvious object name matches the type name:
class FooManager
{
public BarManager BarManager { get; set; } // Feels very wrong.
// Recommended naming convention?
public int DoIt()
{
// 1st and 2nd Bar Manager are different symbols
return BarManager.Blarb + BarManager.StaticBlarb;
}
}
class BarManager
{
public int Blarb { get; set; }
public static int StaticBlarb { get; set; }
}
It seems to compile, but feels so wrong. Is there a recommend naming convention to avoid this?
Having a type and a property with the exact same name isn't uncommon. Yes, it looks a little weird, but renaming properties to avoid this clash looks even weirder, admittedly.
Eric Lippert had a blog post on this exact topic.
There is no ambiguity for the compiler, however.
The c# convention is to name properties in the same way as you name your classes. The reason you feel it's wrong is because you come from a different background. But if you use if for a while you will learn that it doesn't cause you any problems and it will feel pretty natural when you are used to it. There is no place when it will collide in any way. I (as a c# developer) feel that the convention of initial lower case letter for properties feel wrong. You just have to get used to it.
I'm okay with this honestly -- if your static methods/members aren't obviously static by name and by purpose, you've got bigger problems than name collision.
I do not think it has ever caused an issue for me. Following are general conventions, for Properties. Only thing helpful could be getting used to these....
Pascal Case, no underscores.
Try to avoid abbreviations.
Members must differ by more than case
to be usable from case-insensitive
languages like Visual Basic .NET.
Why: This convention is consistent
with the .NET Framework and is easy to
read. like
public int RecordId
reference : NET Programming Standards and Naming Conventions
also check this: General Naming Conventions
I will caviat this by saying, I don't mind the collision, as the compiler can work it out. However, in the spirit of offering other solutions I have seen, and letting others decide for myself... I think this is where the ugly (to me) pattern of using My* arose.
For instance:
public class Foo { /* ... */ }
public class Bar
{
public Foo MyFoo { get; set; }
// ...
}
I often take the classes that linq2sql generates and create a simple data-only class like so
public class myentity
{
public Guid id { get; set; }
public string name { get; set; }
// etc
}
I don't put methods in these classes and I mainly use them as helper classes so I can serialize to/from json and other similar actions, quite easily.
My question is, should I use a struct in this case rather than a class?
It seems to make sense to make it a struct as its more or less the definition of a struct, but I dont know if the performance will be ideal here since I often pass the classes around from method to method and I don't want a ton of copies since structs are value types.
Another thing I do quite often is use Linq2Sql's delayed execution to return my own lightweight version of the Linq2Sql classes, rather than the one they generate. I'm not entirely sure if using a struct instead of a class would have some adverse performance impact here.
an example of how I'd use delayed execution is something like this
public IEnumerable<myentity> getEntities()
{
return from me in MyEntity return new myentity() { id = me.id, name = me.name };
}
public IEnumerable<myentity> getEntitiesThatStartWith(string s)
{
return from me in getEntities() where me.name.StartsWith(s);
}
I'd go with a class. A mutable struct is rarely a good thing. If you don't see a clear advantage of using structs instead of classes, you should avoid it.
Specifically, in your case, using a struct makes it harder for a method to modify contents of an instance (e.g. deserialize from JSON and fill some properties; you'd have to use ref all the time).
Assume Entity is a struct:
List<Entity> entities = ...;
entities[0].Name = "Test"; // won't compile.
I think you've misunderstood the point of structs. You say "it's more or less the definition of a struct" but you haven't mentioned value type semantics (copying) once - and that's the definition of a struct, IMO. It doesn't matter how many methods there are, etc - it's about the value or reference type semantics.
As Mehrdad says, mutable structs are rarely a good thing. I'd put it more strongly: they're almost always evil, and will cause weird bugs which are very hard to diagnose. Just say no - structs are very rarely the right choice in my experience. They're for fundamental data types like numbers, dates, characters, enums etc.
My colleague and I have been having a discussion about what Collections should be called.
For example:
Class Product - Collection - Class Products
or
Class Product - Collection - Class ProductCollection
I've had a look around to see if I can see any guidelines or reasons for using one or the other but nothing seems to spring out. The framework seems to use both variants for example. The argument I can see is that a class that has a collection of products variable should be called Products but it should be of type ProductCollection.
Which is correct if any?
In the same vane is there a standard for the naming of return variable for a function. e.g. retVal?
We mainly code in C#, although I'm not sure that affects my question.
I would say that with generics there should rarely ever be a reason to create a custom collection type. But if you must I would say that ProductCollection would best fit the naming conventions of the framework.
Still, consider using a List<Product> or Collection<Product> or better yet IList<Product> or ICollection<Product>.
Edit: This is in response to MrEdmundo's comments below.
In your case you have two choices. The most obvious choice would be to use inheritance like this:
class Ball { }
class BallCollection : List<Ball>
{
public String Color { get; set; }
public String Material { get; set; }
}
I say obvious because it seems like the best idea at first glance but after a bit of thought it becomes clear that this is not the best choice. What if you or Microsoft creates a new SuperAwesomeList<T> and you want to use that to improve the performance of your BallCollection class? It would be difficult because you are tied to the List<T> class through inheritance and changing the base class would potentially break any code that uses BallCollection as a List<T>.
So what is the better solution? I would recommend that in this case you would be better off to favor composition over inheritance. So what would a composition-based solution look like?
class Ball { }
class BallCollection
{
public String Color { get; set; }
public String Material { get; set; }
public IList<Ball> Balls { get; set; }
}
Notice that I have declared the Balls property to be of type IList<T>. This means that you are free to implement the property using whatever type you wish as long as that type implements IList<T>. This means that you can freely use a SuperAwesomeList<T> at any point which makes this type significantly more scalable and much less painful to maintain.
Products is certainly not correct IMHO. A non-static class name should represent a noun (not plural), because you should be able to say "x is a [classname]".
Obviously, Products doesn't fit in that scheme. ProductCollection does:
Illustration:
var products = new Products(); // products is a Products
var products = new ProductCollection(); // products is a ProductCollection
Which one "sounds right" ?
Another thing about naming collection classes: I usually try to name collection classes in such way that it is clear what kind of collection it is.
For example:
class ProductCollection: can only be enumerated and the Count retrieved (i.e. only implements ICollection interface(s))
class ProductList: a list that can be manipulated using Add(), Insert(), etc. (i.e. implements IList interface(s))
class ProductDictionary: a dictionary of products accessible by some key (i.e. implements IDictionary interface(s))
The last one can be ambiguous if there could be a doubt what the key of the dictionary is, so it's better to specify what the key type is (like ProductDictionaryByString). But to be honest, I rarely name it this way because most of the time the key will be a string anyway.
The .NET Framework frequently uses a "Collection" postfix for its collection types. StringCollection, ObservableCollection, KeyedCollection, etc. So go with ProductCollection.
Noticed nobody answered you on the retVal stuff (Or I could just be getting blind). Although I'm not an expert; on the matter of the retVal issue I'm not 100% sure what you mean by "naming of return variable", but if you mean stuff like this:
public void GetSomething(out object retVal)
{
retVal = ThingFactory.CreateSomething();
}
I would say, no matter what the convention is, don't do it. It's very annoying. Just return the value instead. If you need to return more than one thing, then I would think the method either does more than one thing (which a method shouldn't) or those things should be wrapped up in some sort of logical class that could be returned instead.
If instead by "naming of return variable" you mean stuff like this:
var retVal = ThingFactory.CreateSomething();
Then I would say name the variable according to what it is. What it is going to be used for. If its a list of cars, call it listOfCars, if it's a piece of bread to be eaten later, call it pieceOfBread or pieceOfBreadToBeEatenLater.
Hope that helped and that it wasn't too far off into a field somewhere :p
Thesaurus.com
Look no further. No longer will you mull over pluralized singularity. Just fasten one of these plural-protectors to your object's name:
Jumble
Gob
Trove
Miscellany
Vocab
Load
Agglomeration
Mound
Series
Lexicon
Muster
Glossary
Hoard
Swarm
Group
Cluster
Convoy
Assemblage
Herd
Mob
Batch
Amassment
Pile
Bank
Congregation
Clump
Volume
Set
Reserve
Compilation
Flock
Army
Make it fun.