Skip to content

Commit dba478d

Browse files
ClémentClément
authored andcommitted
Adding an example of an interface containing only a ToString method.
1 parent ab84a2f commit dba478d

5 files changed

Lines changed: 32 additions & 1 deletion

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
class Demo : IToString
2+
{
3+
public string Name{get; set;}
4+
public Demo(string nameP){Name = nameP;}
5+
// public override string ToString(){return "The name attribute contains:" + Name;}
6+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/*
2+
* The question of adding ToString methods to interface is a bit delicate and will certainly not be on any CSCI 1302 exam. The answer is, in short: you cannot force the implementation of a ToString with an interface.
3+
* This is discussed at length at
4+
* https://stackoverflow.com/q/510341
5+
* where an alternative solution is provided (essentially: use an abstract class).
6+
*
7+
* Observe that this would compile just fine, even if Demo does not provide the implementation of a ToString method. Of course, Demo already posses a ToString method, the one every class inherits.
8+
*/
9+
10+
interface IToString
11+
{
12+
string ToString();
13+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using System;
2+
3+
class Program
4+
{
5+
static void Main()
6+
{
7+
Demo test = new Demo("This is a test");
8+
Console.WriteLine(test);
9+
}
10+
}

source/diag/cla/FMember.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ class Person{
44
- name: string
55
# nickName: string
66
+ commonName: string
7-
+ GetName(): string
7+
+ GetName() string
88
+ SetName(nameP: string)
99
- NewName(newNameP)
1010
+ Person()

source/lectures/oop/interface.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ Note that
8383
```
8484
- there is no need for the `override` keyword,
8585

86+
## A ToString
87+
8688
## A More Complicated Example
8789

8890
!include diag/cla/Shape.md

0 commit comments

Comments
 (0)