0
0
C Sharp (C#)programming~20 mins

This keyword behavior in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
This Keyword Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of 'this' in instance method
What is the output of this C# program?
C Sharp (C#)
class Person {
    public string Name;
    public Person(string name) {
        this.Name = name;
    }
    public void PrintName() {
        System.Console.WriteLine(this.Name);
    }
}

var p = new Person("Alice");
p.PrintName();
AAlice
BName
CSystem.Object
DCompilation error
Attempts:
2 left
💡 Hint
Remember 'this' refers to the current object instance.
Predict Output
intermediate
2:00remaining
Using 'this' in static method
What happens when you try to compile and run this C# code?
C Sharp (C#)
class Sample {
    public static void Show() {
        System.Console.WriteLine(this.ToString());
    }
}

Sample.Show();
ARuntime error: NullReferenceException
BPrints the class name 'Sample'
CCompilation error: 'this' is not available in static context
DPrints 'System.Object'
Attempts:
2 left
💡 Hint
Static methods do not have an instance context.
Predict Output
advanced
2:00remaining
Output of 'this' in struct method
What is the output of this C# program?
C Sharp (C#)
struct Point {
    public int X, Y;
    public Point(int x, int y) {
        this.X = x;
        this.Y = y;
    }
    public void Move(int dx, int dy) {
        this.X += dx;
        this.Y += dy;
        System.Console.WriteLine($"{this.X},{this.Y}");
    }
}

var p = new Point(1, 2);
p.Move(3, 4);
ARuntime error
B4,6
CCompilation error: Cannot use 'this' in struct
D1,2
Attempts:
2 left
💡 Hint
Structs are value types but can use 'this' inside instance methods.
Predict Output
advanced
2:00remaining
Output of 'this' in constructor chaining
What is the output of this C# program?
C Sharp (C#)
class Box {
    public int Size;
    public Box() : this(10) {
        System.Console.WriteLine(this.Size);
    }
    public Box(int size) {
        this.Size = size;
        System.Console.WriteLine(this.Size);
    }
}

var b = new Box();
A
10
10
B
0
10
C
10
0
DCompilation error
Attempts:
2 left
💡 Hint
Constructor chaining calls the parameterized constructor first.
🧠 Conceptual
expert
2:00remaining
Behavior of 'this' in extension methods
In C#, what does the this keyword mean in the parameter of an extension method?
AIt refers to the static class containing the extension method
BIt refers to the base class of the extended class
CIt is a syntax error to use 'this' in extension method parameters
DIt refers to the instance of the class the method extends
Attempts:
2 left
💡 Hint
Extension methods add behavior to existing types by using 'this' in the first parameter.