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.
Can anyone give me a practical usage where clone is used, I understand how its done and what are the types in it, but I dont see its practical usage. Also I read it somewhere that it is used to save the state of the object, but I still think that rarely the entire state of object would be so important.
If you have an object y encapsulated (for instance it is private) within object X, but you provide an accessor method (such as getY()) then you risk returning the reference to your private object and that's not good. You don't want client code to be able to get the reference to it. So instead you might copy or clone the object within getY(). As mentioned though copying is probably preferred vs. clone -- see Effective Java item 11.
Here is the example code:
public class X {
private Date y = new Date();
// other code here
public Date getY() {
//this could be bad:
//return y;
//this is good:
return new Date(y);
}
Sometimes you load your object properties to a form then bind each property to a (textbox,combobox, ...), after you do changes to the (textbox, checkbox,...) even if you cancel you can't get the original values, so cloning is the best option,
clone your object then bind, if you want to cancel the original object is always unchanged, this is just one case
Related
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.
Which do you think is better..
if (thing.GetType() == typeof(thisthing))
{
//do stuff for this type of thing.
}
Or give the objects an Enum property
if (thing.TypeName == NamesEnum.thisthing)
{
//do stuff for this type of thing.
}
Neither of these is a particularly extensible or maintainable approach.
It's typically better to design this directly into a virtual method in your type hierarchy, and just call the method. This allows other classes to override and provide custom functionality as appropriate.
In your case, the thisthing type (which should be named ThisThing if you want to follow .NET naming conventions) would just have a DoStuff method which could be virtual if needed, and call it.
It depends:
if (thing.TypeName == NamesEnum.thisthing)
will run more performant then GetType() as, this a simple comparison of 2 numeric values.
But:
if (thing.GetType() == typeof(thisthing))
is more more "flexible": when you do some refactoring, change type name or whatever, this condition will still work.
But will fail in condition, if 2 types belong to 2 different assemblies, instead in first case this still will be matched as equal,as you campare not types but just enum values.
In short, there is no best approach, just most suitable for your needs.
IF you are working with basic types that don't have sub types...
your first example can be shortened nicely to
if (thing is typeof(thisthing))
Depends on the situation really. If you get to a lot of different types you're going to want a switch statement at some point, so I would say option 2 if there are going to be a lot of types.
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 10 years ago.
couldn't find any article about it. So.. is using '*this.*Chart1..' in asp.net, c# useful? Any time savings or why and when should I use it?
Thanks
It's really not ASP.NET-specific at all. It's just part of C#.
Some people suggest that you should always use it to indicate that you're referring to an instance member, as opposed to a static member or a local variable.
Personally I only use it when the qualification is required for disambiguation, e.g.
public Person(string name)
{
this.name = name;
}
Assuming you're in a situation where it doesn't affect the meaning of the code (i.e. where you're not disambiguating), it will have absolutely no effect on the generated IL, so there's no performance harm or benefit.
Note that in the rare case where you want to call an extension method on the current object, you need to use this as well. For example:
public class Foo<T> : IEnumerable<T>
{
// Implementation omitted
public int CountDistinct()
{
return this.Distinct().Count(); // this is required here
}
}
Three common uses for this, as per MSDN:
To qualify members hidden by similar names.
To pass an object as a parameter to other methods
To declare indexers
Refer to documentation for examples.
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 10 years ago.
Is there any difference between auto-implemented properties and manually implemented ones, from a performance point of view?
because as we know they are created at runtime
Auto-properties aren't created at runtime, they are generated at compile time. Very much like using, they are helpful syntactic sugar to reduce the amount of typing you need to do. They simply translate into code you would have written manually anyway.
There is no performance difference. Aside from the backing field name, the resulting code is the same as if you did it manually.
As #dasblinkenlight highlights, the backing name, being a "safe name" (as in, could never create it in C#) can cause serialization issues where the name cannot be handled correctly.
There's no difference. Automatic properties are converted to normal properties at compile time. so this:
public int Prop { get; set; }
is made into something equivalent to this:
private int _PropField;
public int Prop {
get { return _PropField; }
set { _PropField = value; }
}
Auto properties are syntactical sugar means they are shorthand of writing properties
Taken from MSDN :
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 can only be
accessed through the property's get and set accessors.
http://msdn.microsoft.com/en-us/library/bb384054(v=vs.90).aspx
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 10 years ago.
During a code review I presented a method quickly to the team that I had made static and one person agreed that there was no reason for it to not be static and a person disagreed saying that he would not make it static because it wasn't necessary and just to be on the safe side for future modifications and testing.
So I did quite a bit of research and obviously it's a specialized case but I would like to know what you would do in this situation and why?
(Its basically a helper method I call from a few different methods, a very low traffic page. More for my knowledge and learning on Static.)
private IEnumerable<Category> GetCategoryByID(int id, Context context)
{
var categoryQuery = from selectAllProc in context.SelectAll_sp()
where selectAllProc.CategoryID == id
select selectAllProc;
return categoryQuery;
}
Making private methods static is a form of micro-optimization; the method call is slightly faster. But the difference is almost too small to be meaningful.
Generally speaking, you should mark a method static when it:
Doesn't interact in any way with instance members, and
You would like to have the ability to call it without instantiating the class, as in Class.Method()
Ordinarily, methods like your example would go into their own static helper class, if they are used in more than one place.
If I were you I would ask my self the following questions.
Is it something which is related to type or instance of type?
If the answer is yes, I would be slightly inclined to make it static else, make it non static.
If you can give us some more information, the community can come up with some good options.
The first remark that comes to my mind is that by declaring this method static and possibly using it in multiple places in your code you are introducing a Service-locator kind of dependency.
As far as I know the main problem with it is that implicit dependencies are introduced, i.e. they can't be inferred by looking at method signatures.
As a consequence it can be much harder to assess the impact of a modification of your static method on the rest of your system.
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 11 years ago.
Why can't you call methods with c# object initializer syntax?
It seems to me that the property setters are called in the order that they are set in the syntax, so why not allow calls to methods as well? If there is a good reason, I'm missing it.
EDIT
I realize the semantic differences between methods and properties and the technical similarities. The purpose of this question is to probe for a good technical reason that they did not include the feature.
this. __curious_geek, I hear what you are saying, but I'm sure there are some features they haven't included because it wasn't technically feasable.
That's all I'm after. The overwhelming unwelcoming tone is heard loud and clear. Stackoverflow is no longer a "Question and Answer site" but instead a "Defend your question site".
Edit 2
Sample usage:
var mySuperLongVariableNameThatIDontWantToTypeOverAndOverAgainAndIsntThatTheWholePointAnyway = new Thingy
{
Name = "Marty McFly",
AddChildren("Biff","Big Bird","Alf"),
// 1000 other properties and method calls.....
}
The answer is in the name -- object initializer syntax is syntactic sugar to visually group the object's initial state. Methods change the object state, so once it's changed, it's no longer the initial state.
For example: say you buy a car. It is a red coupe with 55,000 miles on it. Then, you decide to drive it. It ends up with 55,500 miles on it. It has changed from its initial state:
var c = new Car() {Color = "Red",
Style = Styles.Coupe,
Mileage = 55000};
// c.Mileage is 55,000
c.Drive();
// c.Mileage is 55,500
In this somewhat contrived example, the method has a side effect and thus changes the object from its initial 55,000mi state to a 55,500mi state. This is not the same thing as buying a car with 55,500 miles on it.
If you really want to do this, you could cheat I suppose...
class C {
int BadProperty {
set {
SomeMethod(value);
}
}
void SomeMethod(int value) {
// here is where you do really, really bad things
}
}
Then call it like this!
var fail = new C { BadProperty = 1 };
what if the method fails ? The basic idea is, it's just a syntactic sugar. Eric Lippert is many time asked about "Why does C# not support feature X?". His answer is always
"because no one designed, specified,
implemented, tested, documented and
shipped that feature." - Eric Lippert.
This is all about orders, the Class have to be initialized with all the fields and all declared methods, before it can be guaranteed to run a method safely.
You can call methods with named parameters, if that is what you are asking about:
someMethod(param1: "Hello World", param2: "Some Other Value");