Optional return in C#.Net
Not in the language, no, but you can make your own:
public struct Optional<T>
{
public bool HasValue { get; private set; }
private T value;
public T Value
{
get
{
if (HasValue)
return value;
else
throw new InvalidOperationException();
}
}
public Optional(T value)
{
this.value = value;
HasValue = true;
}
public static explicit operator T(Optional<T> optional)
{
return optional.Value;
}
public static implicit operator Optional<T>(T value)
{
return new Optional<T>(value);
}
public override bool Equals(object obj)
{
if (obj is Optional<T>)
return this.Equals((Optional<T>)obj);
else
return false;
}
public bool Equals(Optional<T> other)
{
if (HasValue && other.HasValue)
return object.Equals(value, other.value);
else
return HasValue == other.HasValue;
}
}
Note that you won't be able to emulate certain behaviors of Nullable<T>
, such as the ability to box a nullable value with no value to null, rather than a boxed nullable, as it has special compiler support for that (and a some other) behavior.
How to make return value optional for a method,if possible?
You can't make the return value optional.
Your two options are to either return a null
or an empty DataTable
:
return new DataTable();
OR:
return null;
Which one is right? It depends on your application logic and how much null
checking you are willing to do in your calling functions.
Update: (following comment)
This is how to return conditionally (assumes a variable called dataTable):
if(gotTable)
{
return dataTable;
}
else
{
return null;
}
C# Optional Out Parameter
I believe this question is asking about having to assign values inside the method with out parameters, and whether there is any way to circumvent that, i.e. by leaving the values unassigned rather than explicitly having to assign them null
.
e.g. Do you have to write:
public bool OutMethod(out int? output)
{
output = null;
return true;
}
Or is there a way to do something like:
public bool OutMethod(out int? output)
{
return true;
}
With the same result?
Short answer is no, this can't be avoided. See the documentation for an example which includes assigning null
explicitly, and states:
Note that the third argument is assigned to null. This allows methods to return values optionally.
Examples of this can also be found in the .NET framework. e.g. Dictionary<TKey,TValue>
's TryGetValue
method:
public bool TryGetValue(TKey key, out TValue value)
{
int num = this.FindEntry(key);
if (num >= 0)
{
value = this.entries[num].value;
return true;
}
value = default(TValue);
return false;
}
Note the explicit assignment to default(TValue)
C# 4.0 optional out/ref arguments
As already mentioned, this is simply not allowed and I think it makes a very good sense.
However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:
Formal parameters of constructors, methods, indexers and delegate types can be declared optional:
fixed-parameter:
attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
= expression
- A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
- A required parameter cannot appear after an optional parameter in a formal-parameter-list.
- A
ref
orout
parameter cannot have a default-argument.
Equivalent to Java's Optional.orElse in C#
You can use the ??
operator.
Your code will be updated to:
string x = null;
string y = x ?? "NeedToCheckforNull";
See: ?? Operator (C# Reference)
optional/null-able OUT parameter in C#
That looks fine to me. A out
cannot be optional for technical reasons (it needs to point to a valid instance).
Idiomatic optional return values in C#
Exceptions are for exceptional scenario's, not for regular program flow. I guess we're on the same side there.
You would only need an additional return "type" like null
when your method both checks for availability and fetches the resource. Take for example the code to get the contents of a file:
if (File.Exists(...))
{
return false;
}
string contents = File.ReadAllText(...);
...
return true;
This requires no exceptions or null
return values, and if the file is deleted between checking and opening the file, that could then be considered an exceptional scenario.
However when trying to get an entity from the database, you'd want to combine the availability check and fetching the resource, so that only one query is required. There are alot of programmers that do in fact return null
, but since there is no C# law it's hard to keep track of which method does what.
I personally like the bool TryGet(int id, out Entity entity)
style, which clearly indicates it does an availability check and fetches the resource if found. If you prefer returning null
and want to be more explicit about what your function does, you could use Entity GetOrDefault(int id)
as a naming convention. Some framework methods (ie. Linq) are named that way.
In case of returning value types, returning a Nullable<>
probably already states what your method is up to. To complete the circle, C# 7 will (as far as I know) add non-nullable reference types.
In the end it's up to you (and your team) what convention you prefer.
Trying to use optional parameters in c#
The problem is that you're using [Optional]
instead of the C# language integration for optional parameters. As far as the language is concerned (in terms of the method declaration part), num1
is a required parameter, so it has to come before optInput
. The compiler does know about OptionalAttribute
when consuming methods, but not when declaring them.
Assuming you wanted both parameters to be optional, use the language integration for both:
public string UserAnswer(string optInput = null, int num1 = 0)
I would strongly advise against using OptionalAttribute
explicitly - there's no reason to do so now there's language support, and it's more likely to cause confusion than to help when it comes to anyone else reading the code.
Related Topics
Update Float Array from C++ Native Plugin
Recursive Linq Query: Select Item and All Children with Subchildren
Using Xmlarrayitem Attribute Without Xmlarray on Serializable C# Class
How to Lock/Unlock a File Across Process
Ef5 Code First - Changing a Column Type with Migrations
How to Share an Enum Declaration Between C# and Unmanaged C++
Printing a Formatted HTML Page in C#
Feasibility of C# Development with Mono
Best Way to Iterate Folders and Subfolders
How to Convert Xml to JSON Using C#/Linq
How to Share Data Between Different Threads in C# Using Aop
How to Detect Iis Version Using C#
With C# Use Chrome to Covert HTML to Pdf