Function prototype: Difference between revisions
Content added Content deleted
(Added C#) |
|||
Line 131: | Line 131: | ||
int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */ |
int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */ |
||
int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */</lang> |
int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */</lang> |
||
=={{header|C sharp}}== |
|||
'''Abstract methods'''<br/> |
|||
Interfaces and abstract classes can define abstract methods that must be implemented by subclasses. |
|||
<lang csharp>using System; |
|||
abstract class Printer |
|||
{ |
|||
public abstract void Print(); |
|||
} |
|||
class PrinterImpl : Printer |
|||
{ |
|||
public override void Print() { |
|||
Console.WriteLine("Hello world!"); |
|||
} |
|||
}</lang> |
|||
'''Delegates'''<br/> |
|||
A delegate is similar to a function pointer. They are multicast: multiple methods can be attached to them. |
|||
<lang csharp>using System; |
|||
public delegate int IntFunction(int a, int b); |
|||
public class Program |
|||
{ |
|||
public static int Add(int x, int y) { |
|||
return x + y; |
|||
} |
|||
public static int Multiply(int x, int y) { |
|||
return x * y; |
|||
} |
|||
public static void Main() { |
|||
IntFunction func = Add; |
|||
Console.WriteLine(func(2, 3)); //prints 5 |
|||
func = Multiply; |
|||
Console.WriteLine(func(2, 3)); //prints 6 |
|||
func += Add; |
|||
Console.WriteLine(func(2, 3)); //prints 5. Both functions are called, but only the last result is kept. |
|||
} |
|||
}</lang> |
|||
'''Partial methods'''<br/> |
|||
A partial type is a type that is defined in multiple files.<br/> |
|||
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. If it is not implemented, the compiler removes the signature at compile time.<br/> |
|||
The following conditions apply to partial methods:<br/> |
|||
- Signatures in both parts of the partial type must match.<br/> |
|||
- The method must return void.<br/> |
|||
- No access modifiers are allowed. Partial methods are implicitly private. |
|||
<lang csharp>//file1.cs |
|||
public partial class Program |
|||
{ |
|||
partial void Print(); |
|||
} |
|||
//file2.cs |
|||
using System; |
|||
public partial class Program |
|||
{ |
|||
partial void Print() { |
|||
Console.WriteLine("Hello world!"); |
|||
} |
|||
static void Main() { |
|||
Program p = new Program(); |
|||
p.Print(); //If the implementation above is not written, the compiler will remove this line. |
|||
} |
|||
}</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |