开发者

What's the equivalent for pred and succ in C#?

Pascal is my study la开发者_如何学编程nguage and I am curious whether C# also has the functions pred and succ.

This is what I have done in Pascal that I want to try in C#

// in Pascal:
pred(3) = 2
succ(False) = True
pred('b') = 'a'
type enum = (foo, bar, baz);
succ(bar) = baz; pred(bar) = foo

Is the same code applicable for C#, too? If so, what is the namespace for these functions?

(I searched Google, but couldn't find the answer)


There aren't pred and succ functions in C#. You just write n - 1 or n + 1.


You have method overloading in c# so it's easy to have pred and succ, You can do it by:

public int pred(int input)
{
   return input - 1;
}

public char pred(char input)
{
  return (char)((int)input - 1);
}
....


Using extensions:

public static int Pred(this int self) => self - 1;
public static int Succ(this int self) => self + 1;

Then, this would work:

3.Pred() //-> 2
int x = 3;
x.Succ() //-> 4

Probably not considered very idiomatic, but still works. Would have to override for other integer types (like short). Check if the calls get inlined if you're concerned with performance.

Note: ++ and -- act as Inc and Dec, not Succ and Pred.


You can use ++ or -- operator:

3++ = 4
3-- = 2

Not sure why you would need it though when you can just do 3+1 or 3-1 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜