best use for Regions and Inner Regions [closed] - c#

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.
I have see alot of old code and from a lot of developers.
#region #endregion
can be helpful some times but if is use well.
how is the best way to use it to keep my code organized and easy to read?

It doesn't mean anything special if that's what you're asking. The only special effect it has is within Visual Studio for code folding.
If you have a large class that performs a few tasks, it may be best to region it out by separating your properties, different groups of methods, interface implementations, and whatever else you think may be important. There are no strict rules.
class MyReallyBigClass : IAwesome, INotAsAwesome
{
#region Public Properties
public string Test { get; set; }
// ..
#endregion
#region IAwesome Implementation
public void IAwesome.BeAwesome()
{
// ..
}
public int IAwesome.AwesomeLevel()
{
// ..
}
#endregion
#region INotAsAwesome Implementation [[...]]
#region Internal Fields
private int _whatever;
// ..
#endregion
}
Of course in practice, you wouldn't really get a class so large that you'd need to separate it out, but I normally do find myself using it around properties and interface implementations at the least.

It's purely to aid readability in the IDE. It's effectively stripped out on compilation.
That said, I tend to defer to Microsoft's style guidelines with regards to usage: grouping methods, properties, constructors, etc. - rarely, if ever, inside a method, and never between a brace construct (if, for, etc) and the opening brace.

Related

Is 'this.' a useful property? [closed]

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.

Performance differences between automatic propreties and normally declared propreties. True or False? [closed]

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

Would you make this method Static or not? [closed]

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.

Method lines amount. Clean code [closed]

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.
What is the optimal amount of lines in method shold be used?
Curly braces doesn't count.
What code is better? Code is runing in Main()
//1st
string line;
while ((line = Console.ReadLine()).ToLower() != Break)
{
commandAnalyzer.AnalyzeAndRun(line);
}
// or 2nd
RunTextualInterface(commandAnalyzer);
private static void RunTextualInterface(TextCommandAnalyzer commandAnalyzer)
{
while (notBreakCommand())
{
analyzeCommandWithHelpOf(commandAnalyzer);
}
}
private static void analyzeCommandWithHelpOf(TextCommandAnalyzer commandAnalyzer)
{
commandAnalyzer.AnalyzeAndRun(readNewLine());
}
private static bool notBreakCommand()
{
return readNewLine() != Break;
}
private static string readNewLine()
{
return Console.ReadLine().ToLower();
}
// result just the same
P.S I am asking cause out teacher said that every method must have maximum 6 lines.(Curly braces dosn't count)
I think first approach would be better in this case. Too many method will decrease the readability when the logic involved is not too complex and not that large that it should be a separate method. Also it will make sense to make different methods if this logic has to be used by other parts of program as well. But again as the methods are so small, it doesn't even makes sense to me to make a separate method in this case
You want to reduce the amount of code you need to maintain without reducing readability. I like your first answer. Read Steve Yegge on how code size is Code's Worst Enemy.
Strive to keep everything the reader of your code will need to understand your code as local as possible. Use abstractions (e.g. refactoring stuff to methods) where they help. Avoid abstractions (e.g. inventing new names for operations your reader is already familiar with) where they don't help.
As to the various rules on method sizes: They aren't rules. They are guidelines. Whenever your method gets too long, stop. It could be a sign of a bad design. But it doesn't have to be - use the rule to trigger a closer look at your code.
Develop a sense of style. This will change all the time as you progress. Don't be afraid to update your style all the time - though do try to keep the same style during a project. Try out different styles and gain experience. It is the only true path.
If you're interested in that kinda questions, I'd suggest reading:
Code Complete 2nd Edition
The book has a chapter about that:
"Creating high quality code" -> "How long can a routine be?"

What are good resources for learning about generics? [closed]

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.
Can anybody help me where to start and what are the essential things to learn about collections (non-generics) and generics?
Defining Collections
Collections in C#
An introduction to C# Generics
I also recommend the following book which has pretty much all the details you could want on Generics in .NET 2.0 onwards, including Generic classes, methods, delegates and constraints, how they differ from C++ templates, and the generics in the BCL.
.NET 2.0 Generics
For a really brief explanation: Regular collections store objects. The system doesn't know what kind of object is stored, so you have to cast them to the desired type when you work with them. Generic collections declare what kind of object is being put in at the time you create it. Then you always know what is there. it's like the difference between an object array and a String array.
I would definitely check out the list of links on the page PK posted for a more thorough understanding.
1) Classes can be defined with a generic type.
public class MyClass<TClass>
2) The types can be constrained using this syntax.
where TClass: struct
3) Methods also can gave generic types.
public TMethod ConvertTo<TMethod>()
4) Full Example
public class MyClass<TClass> where TClass: struct
{
private TClass _Instance;
public MyClass(TClass instance)
{
_Instance = instance;
}
public TMethod ConvertTo<TMethod>()
{
return (TMethod)Convert.ChangeType(_Instance, typeof(TMethod));
}
}

Categories