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

Casting with as and is operators in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Casting with as and is operators
📖 Scenario: Imagine you have a list of different shapes, but you want to work only with circles. You need to check if each shape is a circle and then get its radius.
🎯 Goal: You will create a list of shapes, check each shape's type using is and as operators, and print the radius of circles.
📋 What You'll Learn
Create a list called shapes with different shape objects
Create a variable called circleCount to count circles
Use a foreach loop with is operator to count circles
Use a foreach loop with as operator to print circle radii
💡 Why This Matters
🌍 Real World
In real programs, you often have collections of different objects and need to work with only some types safely.
💼 Career
Understanding type checking and casting is important for writing safe and clear code in many C# applications.
Progress0 / 4 steps
1
Create the shapes list
Create a list called shapes containing these objects: a Circle with radius 5, a Rectangle with width 4 and height 6, and another Circle with radius 3.
C Sharp (C#)
Need a hint?

Use List<Shape> and add the objects inside curly braces.

2
Create a circle counter
Create an integer variable called circleCount and set it to 0 to count how many circles are in the list.
C Sharp (C#)
Need a hint?

Use int circleCount = 0; to start counting circles.

3
Count circles using is operator
Use a foreach loop with variables shape to go through shapes. Inside the loop, use the is operator to check if shape is a Circle. If yes, increase circleCount by 1.
C Sharp (C#)
Need a hint?

Use if (shape is Circle) inside the loop to check the type.

4
Print circle radii using as operator
Use a foreach loop with variable shape to go through shapes. Inside the loop, use the as operator to cast shape to Circle and store it in a variable called circle. If circle is not null, print "Circle radius: " followed by circle.Radius. Finally, print "Total circles: " followed by circleCount.
C Sharp (C#)
Need a hint?

Use Circle circle = shape as Circle; and check if circle != null before printing.