Returning empty collections - c#

Check out this test:
[TestFixture]
public class Quick_test
{
[Test]
public void Test()
{
Assert.AreEqual(0, GetByYield().Count());
Assert.AreEqual(0, GetByEnumerable().Count());
}
private IEnumerable<string> GetByYield()
{
yield break;
}
private IEnumerable<string> GetByEnumerable()
{
return Enumerable.Empty<string>();
}
}
When I write stub methods I generally use the Enumerable.Empty way of doing it. I stumbled across some old code I wrote where I did it the yield way.
This got me to wondering:
Which is more visually appealing to other developers?
Are there any hidden gotchas that would cause us to prefer one over the other?
Thanks!

I would prefer any method that delivers the clearest meaning to the developer. Personally, I don't even know what the yield break; line is does, so returning 'Enumerable.Empty();` would be preferred in any of my code bases.

Enumerable.Empty : the documentation claims that it "caches an empty sequence". Reflector confirms. If caching behavior matters to you, there's one advantage for Enumerable.Empty

Even faster might be:
T[] e = {};
return e;

Related

Jump to certain line in code C#

I have a few methods that are called from within a few other methods. When in some of the methods a certain action is performed, I would like to go back to the very first method and skip the rest of the code. At the moment, I use booleans to check the "status" of the program but I would like to avoid this because the methods should be void since in essence they don't need to return anything. I found stuff like goto but that only works in the same method.
Question: is there a way to jump to a specific point in the code in a different method in C#? I found stuff on other languages but not a lot on C#.
Current situation:
void test1()
{
bool status = test2();
if (!status)
return; // the other stuff will not get done
Debug.WriteLine("Initialization OK");
}
bool test2()
{
bool status = test3();
if (!status)
return false; // the other stuff will not get done
// do other stuff
return true;
}
bool test3()
{
if (xxx)
return false; // the other stuff will not get done
else
// do other stuff
return true;
}
Wanted situation:
void test1()
{
test2();
// do other stuff
Debug.WriteLine("Initialization OK");
GOTOHERE:
Debug.WriteLine("Initialization NOT OK");
}
void test2()
{
test3();
// do other stuff
}
void test3()
{
if (xxx)
**GOTOHERE**; // Go directly to the location in test1() so that all unnecessary code is skipped
// do other stuff
}
I was surprised to learn that C# does actually support a GOTO command. But it is designed to allow exit from deep nested loops.
This article explains it and gives lots of examples: https://www.dotnetperls.com/goto
However
Unless you are still coding in 1970 then using GOTO is considered very bad practice. It makes code maintenance very difficult. And it even causes problems and performance issues, and makes life for the JIT compiler more difficult.
The go to statement as it stands is just too primitive, it is too much
an invitation to make a mess of one's program.
Edsger W. Dijkstra
Returning something from your method to indicate what you should do afterwards is exactly what you should do. Thus return a boolean indicating if test2 or test3 succeeded and use that value to indicate if you want to proceed further. Don´t use goto nowadays as it only leeds to spaghetti-code, that is hard to maintain. To determine under which circumstances control-flow should jump to GOTOHERE you´d need to scan your entire code for that specific goto-statement.
In your case you want to indicate if some initialization-code works correct. Thus you can also throw an exception:
void test3()
{
if (xxx)
throw new Exception("Some text");
// do other stuff
}
This way you don´t need to return anything from your method, but handle the exception appropriately:
void test1()
{
try { test2(); }
catch {
// some exception-handling such as logging
return;
}
Debug.WriteLine("Initialization OK");
}
This has the advantage that you don´t need to check in test2 if test3 succeeded, allowing you to let the exception bubble through your methods until it is finally handled by a catch. If no catch was found in the entire callstack your app will probably terminate.
C# does have the goto keyword, which works just like in other languages. Declare a label as label_you_want_to_jump_to:, and use goto label_you_want_to_jump_to (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto).
Now that this is said, it is usually a bad idea to use goto, especially in such a way. Your problem might be solved more easily by refactoring a bit. Splitting test3 into two functions, reducing the amount of nesting might be such a way. You may also throw an exception in test3, and catch it in test1. It all depends on what you want to do.
If you get rid of the explicit bools (which are redundant), your (rather contrived) example looks a lot "cleaner" in my opinion:
void test1()
{
if (test2())
{
Debug.WriteLine("Initialization OK");
}
}
bool test2()
{
return test3();
}
bool test3()
{
return xxx;
}
I also prefer to use positive rather than negative conditions, so "if (true)" rather than "if (!false)". This avoids double negatives, which are harder to understand.
Effectively we are using Predicate Logic. We can combine our predicates (methods than return bool without side effects) using the normal logic operators. Consider this example:
bool test4()
{
if (test1())
{
if (test2())
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
We note that this is simply a logical conjunction (and) of test1 and test2, so can simply use the && conjunction operator to make this much clearer:
bool test4()
{
return test1() && test2();
}
Similarly for logical disjunction (or):
bool test5()
{
if (test1())
{
return true;
}
else if (test2())
{
return true;
}
else
{
return false;
}
}
We can write this instead as:
bool test5()
{
return test1() || test2();
}
I don't recommend it, but the simple answer to your question is to use a goto statement.
See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/goto
You should, however, really be returning values from previous method calls that you can use to determine if you need to run other code.
You can also throw exceptions, but in general I'm not a fan of using them for control of flow unless the circumstance is exceptional (hence the name, I suppose). If you expect that control may flow this way or that, it is not exceptional.
I do understand your point but breaking the sequence of events (aka jumping) is not good practice. Your code becomes unreadable because the reader needs to jump from one place to another. There is a reason why you can't jump out of the current method:
What follows is a really simplified explanation. I am glosing over many details.
If you have knowledge about how the stack works you'll know that the runtime will push a new stack frame onto the stack for each new method invocation. That new stack frame contains the method's local variables as well as other things that are implementation details. If you want to jump to another method the runtime would need to push a new stack frame onto your stack in order to create those local variables for that method. So your goto would become a method invocation rather than a jump statement. Which is weird and not what you/we want. Use normal method invocations in such scenarios rather than jump statements.
There are widly accepted jumping statements like return, break and continue. goto is not one of them, although I consider goto case to be a valid solution in some cases.
Returning the information about what to do next is the correct behaviour here.
I do agree that returning a bool is not very expressive from a sematic perspective, at least not whith your current method names. Naming improvement suggestion:
void DoTest1();
bool TryTest2();
bool TryTest3();
FYI
bool flag;
void test1()
{
test2();
if (flag) {
// do other stuff
Debug.WriteLine("Initialization OK");
}
else {
Debug.WriteLine("Initialization NOT OK");
}
}
void test2()
{
test3();
if (flag) {
// do other stuff
}
}
void test3()
{
if (xxx)
return;
// do other stuff
flag = true;
}

Better (legible) way to perform runtime check without adding boilerplate?

I have this piece of code that consumes too much vertical space and it's too verbose.
if (property == null)
{
throw new XamlParseException($"Cannot find a property named \"{Name}\" in the type {underlyingType}");
}
Isn't there an equivalent method, but more legible and compact?
Something in the shape of
ThrowIfNull<XamlParseException>(message)
You can always create an extension method:
public static class ClassContracts {
public static void ThrowIfNull(this Object item)
{
if(item == null) throw new XamlParseException("Your message here", null);
}
}
This way you use up less space which is what you were talking about, and you can use the code over and over whenever you need it. I have a library of these for testing for nulls etc. I like doing it this way over Code Contracts, because that requires the binary rewriter and depending on your environment, your build system (if you have one) may not support doing that. Ultimately, Code Contracts do more than just this, but in a pinch this offers a quick and concise way of checking for nulls and other conditions easily in code as you can create other ones like:
public static void CheckForCondition <T>(this T item, Predicate<T> p, Func<Your_Exception_Type> createException)
{
if(p(item)){throw createException();}
}
With this base method, you can then create other ones and create overloads, etc. have the predicate, or the exception method already created.
public static void CheckForNullCondition<T>(this T item)
{
item.CheckForCondition(x => x == null,
() => new Exception("Item is null"));
}
Extension Methods
I have no knowledge of such method but you can either create it by yourself or just move message to the resources file/internal constant (of course if the space taken by it is the case).
Extension approach is also viable option if it is acceptable for you (I mean having such extension for PropertyInfo or any other type).

Get the Debug.Assert condition as a string on fail

I'm building up tooling for a piece of software and would like to be able save out the boolean expression in the source code that exists in a Debug.Assert (or Trace.Assert) call.
For example, if the program crashes with:
var x = -1;
Debug.Assert(x >= 0, "X must be non-negative", "some detail message");
I'd like to be able to get out the string "x >= 0" as well as the message and detail message.
I've looked into using a TraceListener, but TraceListener#Fail(string) and TraceListener#Fail(string, string) only can capture the message and detail message fields (which, in the case a developer does not include, leaves me with no easy way to report what went wrong).
I suppose it's possible to create a stack trace and read the particular line that failed and report that (assuming the source code is available), but this seems relatively fragile.
Thanks for your time!
You can use expressions to accomplish something rough:
public static class DebugEx
{
[Conditional("DEBUG")]
public static void Assert(Expression<Func<bool>> assertion, string message)
{
Debug.Assert(assertion.Compile()(), message, assertion.Body.ToString());
}
}
and use it like so:
var i = -1;
DebugEx.Assert(() => i > 0, "Message");
There are some down sides to this. The first is, you have to use a lambda, so that complicates the syntax a little bit. The second is since we are dynamically compiling things, there is a performance hit. Since this will only happen in Debug mode (hence the conditional), the performance loss won't be seen in Release mode.
Lastly, the output isn't pretty. It'll look something like this:
(value(WindowsFormsApplication1.Form1+<>c__DisplayClass0).i > 0)
There isn't a whole lot you can do about this. The reason this happens is because of the closure around i. This is actually accurate since that is what it gets compiled down into.
I had already started typing an answer when #vcsjones posted his answer, so I abandoned mine, but I see there are some parts of it that are still relevant. Primarily with regards to formatting the lambda expression into something readable, So I will merge his with that part of my intended answer.
It uses a number of regular expressions to format the assertion expression, so that in many cases it will look decent (i.e. close to what you typed).
For the example given in #vcsjones answer it will now look like this:
Assertion '(i > 0)' failed.
public static class DebugEx
{
private static readonly Dictionary<Regex, string> _replacements;
static DebugEx()
{
_replacements = new Dictionary<Regex,string>()
{
{new Regex("value\\([^)]*\\)\\."), string.Empty},
{new Regex("\\(\\)\\."), string.Empty},
{new Regex("\\(\\)\\ =>"), string.Empty},
{new Regex("Not"), "!"}
};
}
[Conditional("DEBUG")]
public static void Assert(Expression<Func<bool>> assertion, string message)
{
if (!assertion.Compile()())
Debug.Assert(false, message, FormatFailure(assertion));
}
private static string FormatFailure(Expression assertion)
{
return string.Format("Assertion '{0}' failed.", Normalize(assertion.ToString()));
}
private static string Normalize(string expression)
{
string result = expression;
foreach (var pattern in _replacements)
{
result = pattern.Key.Replace(result, pattern.Value);
}
return result.Trim();
}
}

Avoiding repetitive code in multiple similar methods (C#)

Greetings everyone!
I have a set of a few (and potentially will have dozens more) of very similar methods in C#. They all built on almost identical pattern:
ResultObjectType MethodX(...input parameters of various types...)
{
nesting preparation code here...
{
{
resultObject = ExternalClass.GetResultForMethodX(input parameters of MethodX);
}
}
nesting result processing code here ...
return resultObject;
}
Repeating/identical parts: ResultObjectType, preparation code, result processing code.
Different parts: ExternalClass method to call, input parameter set (number of input parameters, their types).
Important: I am not in control of the method signatures – cannot change them.
I am trying to avoid repeating all blocks of similar code with something like this:
ResultObjectType MethodX(...input parameters of various types...)
{
return UniversalMethod(
new ExternalMethodDelegate(ExternalClass.GetResultForMethodX),
input parameters of MethodX...);
}
ResultObjectType UniversalMethod (Delegate d, input parameters of various types...)
{
nesting preparation code...
{
{
resultObject =
(d as ExternalMethodDelegate)(same input parameters as above);
}
}
nesting result processing code...
return resultObject;
}
So far I only managed to make it work in this manner in case where all parameters have the same known type at the time of coding. After a number of attempts to tackle this problem with generic delegates I am starting to think this is not possible to achieve. Even when my code compiles, it does not work at runtime. Any takers? Thanks in advance for your help!
Here's an example using generic delegates:
int MethodY(int something, int other)
{
return UniversalMethod(() => GetResultForMethodY(something, other));
}
string MethodX(string something)
{
return UniversalMethod(() => GetResultForMethodX(something));
}
T UniversalMethod<T>(Func<T> fetcher)
{
T resultObject;
//nesting preparation code here...
{
resultObject = fetcher();
}
//nesting result processing code here ...
return resultObject;
}
If ResultObjectType is always the same then you can remove all Ts.
Repeating/identical parts: ResultObjectType, preparation code, result processing code.
You should concentrate to make this parts as isolated as possible.
Another approach is code generation.

C# -jQuery like function chaining is possible in C#?

As I am new to C# ,just wish to know, can i perform function chaining in C# like jQuery ?
Example jQuery :
$("#gview tbody tr")
.not(":first,:last")
.filter(":odd")
.addClass("someclass")
.css("border","solid 1px grey");
Note : I don't mean clientside script.My only concern is function chaining is possible in C# or not
Yes, just return the current object (this), and you can chain as much as you want. It's also called fluent interface
Yes you need to look into using the Builder Pattern modified to return the object being worked on.
Example:
public class SomeClass
{
public SomeClass doSomeWork()
{
//do some work on this
this.PropertyA = "Somethign";
return this;
}
}
This is also referred to as a chaining design pattern.
Yes, you can, but as with jQuery, the functions you want to chain must be built for it. If you build your own, just return the object the caller should chain on. One example of chaining in C# is Fluent nHibernate.
Yes. I use it regularly, for example with a StringBuilder:
string s =
new StringBuilder()
.Append(year)
.Append('-')
.Append(month)
.Append('-')
.Append(day)
.ToString();
Or with my own library for creating HTML controls:
Container.Controls.Add(
Tag.Div.CssClass("item")
.AddChild(Tag.Span.CssClass("date").Text(item.Date))
.AddChild(Tag.Span.CssClass("title").Text(item.Title))
);
yes,
try this
var s = 19.ToString().Replace("1"," ").Trim().ToString("0.00");
You can call one function from another just like most programming languages... it all depends on how you build.
You could have an object as such:
public class DoMath
{
private int Add2(int piNumber)
{
return piNumber + 2;
}
private int Divideby7(int piNumber)
{
return Divideby7(this.Add2(piNumber));
}
}
Yes, and there are several good examples of how it can be done. For example, take a look at Fluent NHibernate.

Categories