Memoization in Java - c#

Ok so in C# I could write:
public class Memorizer<K,TRes>
{
private Dictionary<K,TRes> _mem;
private Func<K,TRes> _function
public Memorizer (Func<K,TRes> function)
{
_function = function;
_mem= new Dictionary<K,TRes>();
}
public TRes Call(K arg)
{
if (mem.ContainsKey(arg)
{
return _mem[arg];
}
else
{
TRes ret=_function(arg);
_mem[arg] = ret;
return ret;
}
}
}
Which could be made use of for obvious gains:
public class FactorialCalculator()
{
private Memorizer<ushort, ulong> _memorizedFactorial;
public FactorialCalculator()
{
_memorizedFactorial = new Memorizer<ushort, ulong> (innerFactorial);
}
private ulong innerFactorial(ushort x)
{
return (x=0) ? 1 : x*Factorial(x-1)
}
public ulong factorial(ushort x)
{
_memorizedFactorial.Call(x);
}
}
I'm sure it could be made more general and elegant.
And I know I'll have overflow exceptions if x>20.
(And I may have typecast errors in there too)
BUt hopefully I made my point: i can create a class that can furful the needs for memoisation of pure mathematical functions (I.e. deterministic, side-effect free functions)
and get wonderful performance gains.
How can I accomplish a similar thing in Java?

In Java 8 you can use the computeIfAbsent to achieve memoization :
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
public class FactorialCalculator {
public static void main(String[] args) {
Function<Integer, Long> factorialFunction = x -> {
System.out.println("Calculating factorial for " + x);
long fact = 1;
for (int i = 1; i <= x; i++) {
fact *= i;
}
return fact;
};
Function<Integer, Long> memoziedFactorialFunction = memoise(factorialFunction);
System.out.println(memoziedFactorialFunction.apply(5));
System.out.println(memoziedFactorialFunction.apply(5));
System.out.println(memoziedFactorialFunction.apply(5));
System.out.println(memoziedFactorialFunction.apply(5));
System.out.println(memoziedFactorialFunction.apply(6));
System.out.println(memoziedFactorialFunction.apply(6));
}
public static <X, Y> Function<X, Y> memoise(Function<X, Y> fn) {
Map<X, Y> pp = new ConcurrentHashMap<X, Y>();
return (a) -> pp.computeIfAbsent(a, fn);
}
}
Result is :
Calculating factorial for 5
120
120
120
120
Calculating factorial for 6
720
720
More details here http://rdafbn.blogspot.ie/2015/06/memoize-functions-in-java-8.html
Lastly, you can use the cyclops library to remove the boilerplate code of creating memoize generic methods( have a look at http://static.javadoc.io/com.aol.cyclops/cyclops-functions/4.0.2/com/aol/cyclops/functions/Memoise.html)

You can't pass functions as data types in java. To fix this, use an interface.
public interface ReturnFunction<K, V> {
public V getValue(K k);
}
Now you can set innerFactorial to a data type.
public ReturnFunction<Short, Long> innerFactorial = new ReturnFunction<Short, Long>(){
public Long getValue(Short x){
return (x=0) ? 1 : x*Factorial(x-1);
}
};
This lets you pass innerFactorial as a data type:
_memoizedFactorial = new Memorizer<Short, Long> (innerFactorial);
And to call the function you write this:
long someLong = _memoizedFactorial.getValue(someShort);
Also, in Java don't capitalize field or method names. It's not standard and makes the code harder to read.

Check out Guava's cache package. This is what it is for.

You can't create a generic map from <short, ulong> in Java because generic type parameters only bind to reference types. You would have to make it <Short, Long> which involves wrapping primitives and may introduce some overhead into your memoization.
Besides that, the translation to Java is pretty straight-forward. Just be aware, you can only memoize types that provide a useful equals and hashCode implementations, and you need to use a size-bounded, thread-safe, weak-key table such as that provided by MapMaker.

Related

how to use interface and purpose of casting?

i have used interface in both cases. is it my first case use interface ??
here is the my interface and class
interface IAddition {
int Add();
}
interface IMultiplication {
int Multiplication();
}
it is my class
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int Add() {
return (x + y);
}
public int Multiplication() {
return (x * y);
}
}
1st case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
Console.WriteLine("Sum is= " + cal.Add());
Console.WriteLine("Multiplication is= " + cal.Multiplication());
Console.ReadKey();
}
}
And 2nd case is this
class Program {
static void Main(string[] args) {
Calculation cal = new Calculation(20, 30);
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;
Console.WriteLine("Sum is= " + add.Add());
Console.WriteLine("Multiplication is= " + mul.Multiplication());
Console.ReadKey();
}
}
What is the purpose of these 2 lines ??? here what is the purpose of casting ?? Although 1st case have same output
IAddition add = (IAddition)cal;
IMultiplication mul = (IMultiplication)cal;
Only the second case programs to IAddition and IMultiplication interfaces. The first case would work even if the Calculation class did not implement IAddition and IMultiplication.
what is the purpose of casting?
Note that since you declare variables with an explicit interface type, you can safely drop the casts in the declarations of mul and add:
IAddition add = cal;
IMultiplication mul = cal;
You could also rewrite your declarations with implicit type declaration:
var add = (IAddition)cal;
var mul = (IMultiplication)cal;
What is the purpose of these 2 lines?
These lines declare two variables using the interface type implemented by Calculation. They make no practical difference in this example, but generally you could use add and mul to be specific about the level of abstraction to which you program. For example, IAddition add tells the readers of your program that you do not need to use any aspects of cal except these related to addition.
The other answers cover the given example code, but it's worthwhile to add that the rules are different for explicit interface implementation.
For example, if the example class was implemented as follows:
public class Calculation : IAddition, IMultiplication {
int x, y;
public Calculation(int x, int y) {
this.x = x;
this.y = y;
}
public int IAddition.Add() {
return (x + y);
}
public int IMultiplication.Multiplication() {
return (x * y);
}
}
then the cast is required. For example:
Calculation cal = new Calculation(10, 10);
cal.Multiplication(); // this will cause a compiler error
((IMultiplication)cal).Multiplication(); // This is the required way to do it
For more information see this article on MSDN
In this case, the purpose is just to show you how you can cast types. It doesn't make a difference in how the code works, but you can see that if you were to try add.Multiplication(), the compiler would tell you that's not allowed.
In a simple example like this, there's no reason to cast and declare variables like this. However, in larger applications, the Interface Segregation Principle helps us to avoid tight coupling of different pieces of code. For example, you could write a method like this:
int SumAll(IAddition adder, params int[] values)
{
int sum = 0;
foreach(int n in values)
{
sum = adder.Add(sum, values[i]);
}
return sum;
}
The above method would work just fine if you pass it a Calculator, but it doesn't have to use a Calculator. Since you know you don't need to multiply anything in this method, this limits your dependencies to the things that you actually need. You might in the future find it useful to implement an Add method with a ceiling, for example, that never allows numbers to go above a certain number, no matter how many things get added. Passing that IAddition object into SumAll would have a different effect, and you wouldn't have to create a different SumAll method to accommodate this need.
Console.WriteLine(SumAll(new Calculator(), 1, 2)); // 3
Console.WriteLine(SumAll(new Calculator(), 1, 2, 3)); // 6
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2)); // 3
Console.WriteLine(SumAll(new AdderWithMax(4), 1, 2, 3)); // 4
In general, people find that by separating interfaces intelligently, they're able to write code that's easier to test and less likely to require as much work when changes are made in the future--in other words, more maintainable code.
Oh, and by the way, the explicit cast isn't actually necessary, so this would also have the same effect:
IAddition add = cal;
or:
var add = (IAddition)cal;
how to use interface
There are many ways to use an inteface, from implementation to type-checking.
// Definition of interface or sometimes referred to as "Contract"
// Implementing classes must define these methods and properties
public interface IMyInterface
{
void MyMethod();
int MyProperty { get; }
}
// Implementation or sometimes referred to as "Concrete type"
public class MyClass : IMyInterface
{
public void MyMethod();
public int MyProperty { get; set; }
}
// Compile time type checking:
public void MyMethod<T>(T value)
where T : IMyInterface
{ }
// Runtime checking
public void MyMethod(object someobject)
{
var myinterface = someobject as IMyInterface;
if (myinterface != null)
{
//someobject implements IMyInterface so I can do things with it
someobject.MyMethod();
}
}
and purpose of casting?
The purpose of casting is has many uses. I'll mostly be demonstrating use the as keyword because it provides type-safety for the run-time.
You can use it to validate a type implements an interface at run-time:
public MyMethod(object obj)
{
var calc = obj as ICalc;
if (calc != null)
{
calc.Calculate();
}
}
This can be improved:
public void MyMethod(ICalc calc)
{
calc.Calculate();
}
Using generics and compile time type safety (I think it's important to show).
public void MyMethod<TObject>(TObject calc)
where TObject : ICalc
{
calc.Calculate();
}
is it my first case use interface ??
I'm not sure what this means, I think what you are trying to say is
Am I required to use the interface by casting it?
No you are not. Lets take a look at these two classes:
public class Calculation1 : IAddition, IMultiplication {
public int Add() { //... ignoring implemenetation
}
public int Multiplication() { //... ignoring implemenetation
}
}
public class Calculation2 {
public int Add() {//... ignoring implemenetation
}
public int Multiplication() {//... ignoring implemenetation
}
}
Both of the classes implement the same methods so these are valid:
var one = new Calculation1();
one.Add();
var two = new Calculation1();
two.Add();
However because the first one implements an interface and the second one does not, you can pass the first object to methods that do not need to know the concrete type.
public void MethodNeedsToAdd(IAddition addCalculator)
{
if (addCalculator != null)
{
addCalculator.Add();
}
}
MethodNeedsToAdd(one); // Valid
MethodNeedsToAdd(two); // Invalid
Even though you and I can clearly see they both can "Add" the second class two does not implement the interface.
It's all about concealing complexity. When you do this cast ...
IAddition add = (IAddition)cal;
You can then handle this add item as if all it can do is implement your IAddition interface. That might prove convenient if you were implementing a complex system.
For example, you might define an IGetNextItem interface. Then, you might choose to implement that interface in a class which fetched an item from a DBMS, and another which generated a random fake item. You would be able to cast either object, and then pass it to some software which consumed those items, without needing to tell the consuming software exactly how the fetching of items actually works.
You don't need the cast. You can say...
IAddition add = cal;
However, the point of that is you are creating an object of any type that implements the IAddition interface.

c# how to passing functions as string to methods

Is it possible to pass a function (like let's say sin() ) via string and then use it as int?
Like: (main idea only)
public int getfunc(String func)
{
return res_of(func)
}
I tried playing around with string of "Math.sin(0)"
but couldn't print the 0...
I could predefine the math functions since I only need 1 and then it becomes extremely simple as I only pass the int value for the function to work on, but I thought may-hap there is a way to keep it more generic.
I do not want to use mapping of the functions I want to keep it dynamic....
is ther a way of doing so?
I'd like to offer an alternative approach that you may not have considered.
You could use a delegate instead of passing a string; that way, you won't need any reflection.
There's a predefined delegate type in C# called Func<> which lets you easily define the return type and parameter types of a method that you want to pass as a delegate.
For example, the Func<> for Math.Sin(double) would be Func<double, double> because Math.Sin() returns a double and takes a double parameter.
An example will make this clearer:
using System;
namespace Demo
{
internal class Program
{
private void run()
{
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Cos;
double r1 = runFunc(f1, 1.0);
double r2 = runFunc(f2, 2.0);
Console.WriteLine(r1);
Console.WriteLine(r2);
}
private static double runFunc(Func<double, double> func, double parameter)
{
return func(parameter);
}
private static void Main()
{
new Program().run();
}
}
}
Try using http://www.csscript.net/
dynamic script = CSScript.Evaluator
.LoadCode(#"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
int result = script.Sum(1, 2);
Declare the method like this:
public int DoCalculation(Func<double, double> func, double a)
{
return Convert.ToInt32(func(a));
}
Then use it like this:
int result = DoCalculation(Math.Sin, 3.3);
In our application we use the .NET integrated C# compiler.
This is some work to do but straight-forward to implement.
Here's an answer with a lot more details on that.
We use this in our companies production.

Dictionary with limited number of types

First, excuse the rather funny name of my question. I'm no native speaker and it took me 10 minutes to express my thoughts in these few characters.
What I'm trying to do is to create a dictionary in C# that allows the value to be either an int, a string or a bool. What first had come to my mind was using generics, but as far as I know, I can only define one type as possible value-type, not "be one of those". Using object would also be possible, but boxing seems to be quite a performance-killer.
Is there any way to do this?
Here's a sample of what has come to my mind:
Dictionary<string, (string, int, bool)> foo = new Dictionary<string, (string, int, bool)>();
foo.Add("key1", "Hello, World!"); //Correct - Value is a string
foo.Add("key2", 37); //Correct - Value is an int
foo.Add("key3", true); //Correct - Value is a boolean
foo.Add("key4", new Foobar()); //Compiler error - Value is a Foobar
My ultimate goal is to provide a library for other developers. This feature should enable them to define "variables" during runtime and give them a type.
Edit://Firefox' about:config page has something very close to what I want to achieve
Why not create a fresh new class which implements the IDictionary and uses a Dictionary as a private variable.
Then, in the add methods, you can provide your own logic and fail accordingly
Sample code
public class MyDic : IDictionary<object, object>
{
private Dictionary<object, object> privateDic= new Dictionary<object,object>();
public void Add(object key, object value)
{
if (value.GetType() == typeof(string))
throw new ArgumentException();
privateDic.Add(key, value);
}
//Rest of the interface follows
}
I would suggest to:
Create a base type for your dictionary values e.g. MyDictionaryBaseType
Extend this basic type for each dictionary value type your have e.g. StringDictionryType : MyDictionaryBaseType, IntegerDictionryType : MyDictionaryBaseType...etc.
Create a generic dictionary type with MyDictionaryBaseType and limit the type to extend this base type.
This way you limit your dictionry to three specifed types
You can put the values into wrapper classs like this:
class Value
{
}
class TypedValue<T> : Value
{
public T Val;
}
class IntValue : TypedValue<int>
{
}
class StringValue : TypedValue<string>
{
}
class BoolValue : TypedValue<bool>
{
}
Dictionary<string,Value> foo;
foo.Add("key1", new StringValue{Val="Hello World!"});
Another possibility would be to use a Dictionary and do a runtime check for right or wrong types added. I don't think there is a solution without involving boxing.
What you are trying to accomplish isn't type-safe as it stands. For example, let's say you have such a dictionary:
var foo = new Dictionary<string, (string, int, bool)>();
var x = foo["key1"];
// What type is x? How could the compiler know?
One idea would be to devise a container class which can hold one-of either string, int, or bool.
public class StringIntBool {
private bool _isSet;
private bool _isString;
public bool IsString {
get { return _isString; }
}
// ...
private string _innerString;
public string InnerString {
get {
return _innerString;
}
set {
if (_isSet) {
throw new Exception("StringIntBool is already set");
}
_isSet = true;
_isString = true;
_innerString = value;
}
}
// etc...
}
This is quite ugly, and doesn't really give many benefits.
As an alternative, you could actually store all three values as objects, and then use a technique / library like Functional C# to perform pattern-matching, like many functional languages can.
object x = "str";
int res = x.Match()
.With<string>(s => s == "str" ? 10 : 20)
.With<int>(i => i)
.With<bool>(b => b ? 50 : 60)
.Return<int>();
This pattern of programming is actually pretty common in certain functional language. For example, in SML, you can define a datatype, and then pattern-match it as needed.
(* StringIntBool *)
datatype sib = SibString of string | SibInt of int | SibBool of bool
val x = (* some instance of sib *)
val y = case x of
SibString s => if s = "hello" then 50 else -50
| SibInt i => i
| SibBool b => if b then 10 else 20

Generics - where T is a number? [duplicate]

This question already has answers here:
Is there a constraint that restricts my generic method to numeric types?
(24 answers)
Closed 8 years ago.
I'm trying to figure a way to create a generic class for number types only, for doing some calculations.
Is there a common interface for all number types (int, double, float...) that I'm missing???
If not, what will be the best way to create such a class?
UPDATE:
The main thing I'm trying to achieve is checking who is the bigger between two variables of type T.
What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).
This has methods like T Add<T>(T x, T y), and other variants for arithmetic on different types (like DateTime + TimeSpan).
Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.
Some additional background on why this is tricky is here.
You may also want to know that dynamic (4.0) sort-of solves this issue indirectly too - i.e.
dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect
Re the comment about < / > - you don't actually need operators for this; you just need:
T x = ..., T y = ...
int c = Comparer<T>.Default.Compare(x,y);
if(c < 0) {
// x < y
} else if (c > 0) {
// x > y
}
There are interfaces for some of the operations on the number types, like the IComparable<T>, IConvertible and IEquatable<T> interfaces. You can specify that to get a specific functionality:
public class MaxFinder<T> where T : IComparable<T> {
public T FindMax(IEnumerable<T> items) {
T result = default(T);
bool first = true;
foreach (T item in items) {
if (first) {
result = item;
first = false;
} else {
if (item.CompareTo(result) > 0) {
result = item;
}
}
}
return result;
}
}
You can use delegates to expand a class with type specific operations:
public class Adder<T> {
public delegate T AddDelegate(T item1, T item2);
public T AddAll(IEnumerable<T> items, AddDelegate add) {
T result = default(T);
foreach (T item in items) {
result = add(result, item);
}
return result;
}
}
Usage:
Adder<int> adder = new Adder<int>();
int[] list = { 1, 2, 3 };
int sum = adder.AddAll(list, delegate(int x, int y) { return x + y; });
You can also store delegates in the class, and have different factory methods that sets up delegates for a specific data type. That way the type specific code is only in the factory methods.
Closest you get is struct I'm afraid. You'll have to do more extensive checks for number types in code.
public class MyClass<T> where T : struct
(...)
You cannot do this, since you'd have to use a single interface for arithmetic operations. There have been many requests on Connect to add an IArithmetic interface for this specific purpose, but so far they've all been rejected.
You can sort of work around this by defining a struct with no members, which implements a "Calculator" interface. We took this approach in an interpolation generic class in the Pluto Toolkit. For a detailed example, we have a "vector" calculator implementation here, which lets our generic interpolator work with vectors. There are similar ones for floats, doubles, quaternions, etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericPratice1
{
public delegate T Del<T>(T numone, T numtwo)where T:struct;
class Class1
{
public T Addition<T>(T numone, T numtwo) where T:struct
{
return ((dynamic)numone + (dynamic)numtwo);
}
public T Substraction<T>(T numone, T numtwo) where T : struct
{
return ((dynamic)numone - (dynamic)numtwo);
}
public T Division<T>(T numone, T numtwo) where T : struct
{
return ((dynamic)numone / (dynamic)numtwo);
}
public T Multiplication<T>(T numone, T numtwo) where T : struct
{
return ((dynamic)numone * (dynamic)numtwo);
}
public Del<T> GetMethodInt<T>(int ch) where T:struct
{
Console.WriteLine("Enter the NumberOne::");
T numone =(T) Convert.ChangeType((object)(Console.ReadLine()), typeof(T));
Console.WriteLine("Enter the NumberTwo::");
T numtwo = (T)Convert.ChangeType((object)(Console.ReadLine()), typeof(T));
T result = default(T);
Class1 c = this;
Del<T> deleg = null;
switch (ch)
{
case 1:
deleg = c.Addition<T>;
result = deleg.Invoke(numone, numtwo);
break;
case 2: deleg = c.Substraction<T>;
result = deleg.Invoke(numone, numtwo);
break;
case 3: deleg = c.Division<T>;
result = deleg.Invoke(numone, numtwo);
break;
case 4: deleg = c.Multiplication<T>;
result = deleg.Invoke(numone, numtwo);
break;
default:
Console.WriteLine("Invalid entry");
break;
}
Console.WriteLine("Result is:: " + result);
return deleg;
}
}
class Calculator
{
public static void Main(string[] args)
{
Class1 cs = new Class1();
Console.WriteLine("Enter the DataType choice:");
Console.WriteLine("1 : Int\n2 : Float");
int sel = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the choice::");
Console.WriteLine("1 : Addition\n2 : Substraction\3 : Division\4 : Multiplication");
int ch = Convert.ToInt32(Console.ReadLine());
if (sel == 1)
{
cs.GetMethodInt<int>(ch);
}
else
{
cs.GetMethodInt<float>(ch);
}
}
}
}
In the Framework BCL (base class library), many numeric functions (such as the functions in System.Math) deal with this by having overloads for each numeric type.
The static Math class in the BCL contains static methods, which you can call without having to create an instance of the class. You could do the same in your class. For example, Math.Max has 11 overloads:
public static byte Max(byte val1, byte val2);
public static decimal Max(decimal val1, decimal val2);
public static double Max(double val1, double val2);
public static short Max(short val1, short val2);
public static int Max(int val1, int val2);
public static long Max(long val1, long val2);
public static sbyte Max(sbyte val1, sbyte val2);
public static float Max(float val1, float val2);
public static ushort Max(ushort val1, ushort val2);
public static uint Max(uint val1, uint val2);
public static ulong Max(ulong val1, ulong val2);
I don't believe you can define that using a generic type constraint. Your code could internally check your requirements, possibly using Double.Parse or Double.TryParse to determine if it is a number--or if VB.NET isn't out of the question then you could use the IsNumeric() function.
Edit: You can add a reference to Microsoft.VisualBasic.dll and call the IsNumeric() function from c#
You can not do it at compile time only.
But you could put more constraints to weed out most of 'bad types' on your numeric type like below
class yourclass <T>where T: IComparable, IFormattable, IConvertible, IComparabe<T>, IEquatable<T>, struct {...
In the end you would still have to check at runtime if your type is acceptable using object.GetType() method.
If only comparing, then IComparable<T> alone does the trick.

Return multiple values to a method caller

I read the C++ version of this question but didn't really understand it.
Can someone please explain clearly if it can be done in C#, and how?
In C# 7 and above, see this answer.
In previous versions, you can use .NET 4.0+'s Tuple:
For Example:
public Tuple<int, int> GetMultipleValue()
{
return Tuple.Create(1,2);
}
Tuples with two values have Item1 and Item2 as properties.
Now that C# 7 has been released, you can use the new included Tuples syntax
(string, string, string) LookupName(long id) // tuple return type
{
... // retrieve first, middle and last from data storage
return (first, middle, last); // tuple literal
}
which could then be used like this:
var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");
You can also provide names to your elements (so they are not "Item1", "Item2" etc). You can do it by adding a name to the signature or the return methods:
(string first, string middle, string last) LookupName(long id) // tuple elements have names
or
return (first: first, middle: middle, last: last); // named tuple elements in a literal
They can also be deconstructed, which is a pretty nice new feature:
(string first, string middle, string last) = LookupName(id1); // deconstructing declaration
Check out this link to see more examples on what can be done :)
You can use three different ways
1. ref / out parameters
using ref:
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add = 0;
int multiply = 0;
Add_Multiply(a, b, ref add, ref multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
add = a + b;
multiply = a * b;
}
using out:
static void Main(string[] args)
{
int a = 10;
int b = 20;
int add;
int multiply;
Add_Multiply(a, b, out add, out multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
add = a + b;
multiply = a * b;
}
2. struct / class
using struct:
struct Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}
using class:
class Result
{
public int add;
public int multiply;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.add);
Console.WriteLine(result.multiply);
}
private static Result Add_Multiply(int a, int b)
{
var result = new Result
{
add = a * b,
multiply = a + b
};
return result;
}
3. Tuple
Tuple class
static void Main(string[] args)
{
int a = 10;
int b = 20;
var result = Add_Multiply(a, b);
Console.WriteLine(result.Item1);
Console.WriteLine(result.Item2);
}
private static Tuple<int, int> Add_Multiply(int a, int b)
{
var tuple = new Tuple<int, int>(a + b, a * b);
return tuple;
}
C# 7 Tuples
static void Main(string[] args)
{
int a = 10;
int b = 20;
(int a_plus_b, int a_mult_b) = Add_Multiply(a, b);
Console.WriteLine(a_plus_b);
Console.WriteLine(a_mult_b);
}
private static (int a_plus_b, int a_mult_b) Add_Multiply(int a, int b)
{
return(a + b, a * b);
}
You cannot do this in C#. What you can do is have a out parameter or return your own class (or struct if you want it to be immutable).
Using out parameter
public int GetDay(DateTime date, out string name)
{
// ...
}
Using custom class (or struct)
public DayOfWeek GetDay(DateTime date)
{
// ...
}
public class DayOfWeek
{
public int Day { get; set; }
public string Name { get; set; }
}
In C#7 There is a new Tuple syntax:
static (string foo, int bar) GetTuple()
{
return ("hello", 5);
}
You can return this as a record:
var result = GetTuple();
var foo = result.foo
// foo == "hello"
You can also use the new deconstructor syntax:
(string foo) = GetTuple();
// foo == "hello"
Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple<string, int> (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.
So, for serialisation declare a record class and return that instead.
Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:
if(int.TryParse("123", out int result)) {
// Do something with result
}
However, mostly you'll use this in .NET's own libraries, rather than in you own functions.
If you mean returning multiple values, you can either return a class/struct containing the values you want to return, or use the "out" keyword on your parameters, like so:
public void Foo(int input, out int output1, out string output2, out string errors) {
// set out parameters inside function
}
There is many way; but if you don't want to create a new Object or structure or something like this you can do like below after C# 7.0 :
(string firstName, string lastName) GetName(string myParameter)
{
var firstName = myParameter;
var lastName = myParameter + " something";
return (firstName, lastName);
}
void DoSomethingWithNames()
{
var (firstName, lastName) = GetName("myname");
}
Previous poster is right. You cannot return multiple values from a C# method. However, you do have a couple of options:
Return a structure that contains multiple members
Return an instance of a class
Use output parameters (using the out or ref keywords)
Use a dictionary or key-value pair as output
The pros and cons here are often hard to figure out. If you return a structure, make sure it's small because structs are value type and passed on the stack. If you return an instance of a class, there are some design patterns here that you might want to use to avoid causing problems - members of classes can be modified because C# passes objects by reference (you don't have ByVal like you did in VB).
Finally you can use output parameters but I would limit the use of this to scenarios when you only have a couple (like 3 or less) of parameters - otherwise things get ugly and hard to maintain. Also, the use of output parameters can be an inhibitor to agility because your method signature will have to change every time you need to add something to the return value whereas returning a struct or class instance you can add members without modifying the method signature.
From an architectural standpoint I would recommend against using key-value pairs or dictionaries. I find this style of coding requires "secret knowledge" in code that consumes the method. It must know ahead of time what the keys are going to be and what the values mean and if the developer working on the internal implementation changes the way the dictionary or KVP is created, it could easily create a failure cascade throughout the entire application.
You either return a class instance or use out parameters. Here's an example of out parameters:
void mymethod(out int param1, out int param2)
{
param1 = 10;
param2 = 20;
}
Call it like this:
int i, j;
mymethod(out i, out j);
// i will be 20 and j will be 10
Some answers suggest using out parameters but I recommend
not using this due to they don’t work with async methods. See
this for more information.
Other answers stated using Tuple, which I would recommend too but using the new feature introduced in C# 7.0.
(string, string, string) LookupName(long id) // tuple return type
{
... // retrieve first, middle and last from data storage
return (first, middle, last); // tuple literal
}
var names = LookupName(id);
WriteLine($"found {names.Item1} {names.Item3}.");
Further information can be found here.
<--Return more statements like this you can -->
public (int,string,etc) Sample( int a, int b)
{
//your code;
return (a,b);
}
You can receive code like
(c,d,etc) = Sample( 1,2);
I hope it works.
No, you can't return multiple values from a function in C# (for versions lower than C# 7), at least not in the way you can do it in Python.
However, there are a couple alternatives:
You can return an array of type object with the multiple values you want in it.
private object[] DoSomething()
{
return new [] { 'value1', 'value2', 3 };
}
You can use out parameters.
private string DoSomething(out string outparam1, out int outparam2)
{
outparam1 = 'value2';
outparam2 = 3;
return 'value1';
}
There are several ways to do this. You can use ref parameters:
int Foo(ref Bar bar) { }
This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int and (potentially) modify bar.
Another similar approach is to use an out parameter. An out parameter is identical to a ref parameter with an additional, compiler enforced rule. This rule is that if you pass an out parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out parameter works just like a ref parameter.
The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:
class FooBar
{
public int i { get; set; }
public Bar b { get; set; }
}
FooBar Foo(Bar bar) { }
This final approach is simpler and easier to read and understand.
In C# 4, you will be able to use built-in support for tuples to handle this easily.
In the meantime, there are two options.
First, you can use ref or out parameters to assign values to your parameters, which get passed back to the calling routine.
This looks like:
void myFunction(ref int setMe, out int youMustSetMe);
Second, you can wrap up your return values into a structure or class, and pass them back as members of that structure. KeyValuePair works well for 2 - for more than 2 you would need a custom class or struct.
you can try this "KeyValuePair"
private KeyValuePair<int, int> GetNumbers()
{
return new KeyValuePair<int, int>(1, 2);
}
var numbers = GetNumbers();
Console.WriteLine("Output : {0}, {1}",numbers.Key, numbers.Value);
Output :
Output : 1, 2
Classes, Structures, Collections and Arrays can contain multiple values. Output and reference parameters can also be set in a function. Return multiple values is possible in dynamic and functional languages by means of tuples, but not in C#.
When your method is async and you want to return multiple properties. You must do like this:
public async Task<(int, int)> GetMultipleValues(){
return (1,2);
}
Mainly two methods are there.
1. Use out/ref parameters
2. Return an Array of objects
Here are basic Two methods:
1) Use of 'out' as parameter
You can use 'out' for both 4.0 and minor versions too.
Example of 'out':
using System;
namespace out_parameter
{
class Program
{
//Accept two input parameter and returns two out value
public static void rect(int len, int width, out int area, out int perimeter)
{
area = len * width;
perimeter = 2 * (len + width);
}
static void Main(string[] args)
{
int area, perimeter;
// passing two parameter and getting two returning value
Program.rect(5, 4, out area, out perimeter);
Console.WriteLine("Area of Rectangle is {0}\t",area);
Console.WriteLine("Perimeter of Rectangle is {0}\t", perimeter);
Console.ReadLine();
}
}
}
Output:
Area of Rectangle is 20
Perimeter of Rectangle is 18
*Note:*The out-keyword describes parameters whose actual variable locations are copied onto the stack of the called method, where those same locations can be rewritten. This means that the calling method will access the changed parameter.
2) Tuple<T>
Example of Tuple:
Returning Multiple DataType values using Tuple<T>
using System;
class Program
{
static void Main()
{
// Create four-item tuple; use var implicit type.
var tuple = new Tuple<string, string[], int, int[]>("perl",
new string[] { "java", "c#" },
1,
new int[] { 2, 3 });
// Pass tuple as argument.
M(tuple);
}
static void M(Tuple<string, string[], int, int[]> tuple)
{
// Evaluate the tuple's items.
Console.WriteLine(tuple.Item1);
foreach (string value in tuple.Item2)
{
Console.WriteLine(value);
}
Console.WriteLine(tuple.Item3);
foreach (int value in tuple.Item4)
{
Console.WriteLine(value);
}
}
}
Output
perl
java
c#
1
2
3
NOTE: Use of Tuple is valid from Framework 4.0 and above.Tuple type is a class. It will be allocated in a separate location on the managed heap in memory. Once you create the Tuple, you cannot change the values of its fields. This makes the Tuple more like a struct.
A method taking a delegate can provide multiple values to the caller. This borrows from my answer here and uses a little bit from Hadas's accepted answer.
delegate void ValuesDelegate(int upVotes, int comments);
void GetMultipleValues(ValuesDelegate callback)
{
callback(1, 2);
}
Callers provide a lambda (or a named function) and intellisense helps by copying the variable names from the delegate.
GetMultipleValues((upVotes, comments) =>
{
Console.WriteLine($"This post has {upVotes} Up Votes and {comments} Comments.");
});
From this article, you can use three options as posts above said.
KeyValuePair is quickest way.
out is at the second.
Tuple is the slowest.
Anyway, this is depend on what is the best for your scenario.
Future version of C# is going to include named tuples.
Have a look at this channel9 session for the demo
https://channel9.msdn.com/Events/Build/2016/B889
Skip to 13:00 for the tuple stuff. This will allow stuff like:
(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}
int resultsum = Tally(numbers).sum
(incomplete example from video)
Just use in OOP manner a class like this:
class div
{
public int remainder;
public int quotient(int dividend, int divisor)
{
remainder = ...;
return ...;
}
}
The function member returns the quotient which most callers are primarily interested in. Additionally it stores the remainder as a data member, which is easily accessible by the caller afterwards.
This way you can have many additional "return values", very useful if you implement database or networking calls, where lots of error messages may be needed but only in case an error occurs.
I entered this solution also in the C++ question that OP is referring to.
You could use a dynamic object. I think it has better readability than Tuple.
static void Main(string[] args){
var obj = GetMultipleValues();
Console.WriteLine(obj.Id);
Console.WriteLine(obj.Name);
}
private static dynamic GetMultipleValues() {
dynamic temp = new System.Dynamic.ExpandoObject();
temp.Id = 123;
temp.Name = "Lorem Ipsum";
return temp;
}
Ways to do it:
1) KeyValuePair (Best Performance - 0.32 ns):
KeyValuePair<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
return new KeyValuePair<int,int>(p_2 - p_1, p_4-p_3);
}
2) Tuple - 5.40 ns:
Tuple<int, int> Location(int p_1, int p_2, int p_3, int p_4)
{
return new Tuple<int, int>(p_2 - p_1, p_4-p_3);
}
3) out (1.64 ns) or ref
4) Create your own custom class/struct
ns -> nanoseconds
Reference: multiple-return-values.
You can also use an OperationResult
public OperationResult DoesSomething(int number1, int number2)
{
// Your Code
var returnValue1 = "return Value 1";
var returnValue2 = "return Value 2";
var operationResult = new OperationResult(returnValue1, returnValue2);
return operationResult;
}
As an alternative you could set your method to void and not return anything. Instead create a public class with parameters and set them inside your method.
public class FooBar()
{
public string foo { get; set; }
public int bar { get; set; }
}
Then for your method try this
public void MyMethod(Foo foo, Bar bar)
{
FooBar fooBar = new FooBar();
fooBar.foo = "some string";
fooBar.bar = 1;
}
you can try this
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

Categories