C# — objects

Michal Molka
4 min readNov 8, 2024

--

In the last article we’ve been working with C# functions: C# — functions. Functions are block of code which we… | by Michal Molka | Oct, 2024 | Medium

Now, it’s time for objects.

C# is an object-oriented programming language where everything is an object. This article shows how to work with objects.

This is a simple object with three fields:

public class ClassA()
{
public int firstValue;
private int secondValue;
private int thirdValue;
}

Fields are something like variables inside an object instance.

As you see in the example, we have three fields. Each of them has an access modifier applied. In this case, public means that a field is available outside the class. Private is available only inside a class. A more detailed description is available in MS Docs.

Here is the code. We will disassembly it step by step.

namespace csharp_objects;

public class ClassA
{
public int firstValue;
private int secondValue;
private int thirdValue;

public ClassA(int field01Value)
{
this.secondValue = field01Value;
}

public int ThirdValue
{
get
{
return thirdValue;
}
set
{
this.thirdValue = value;
}
}

public string ReturnValues()
{
this.firstValue = this.firstValue + 15;
string finalString = $"A first value: {this.firstValue}, a second value: {this.secondValue}, a third value: {this.thirdValue}.";
return finalString;
}

public int ReturnValues(int loopCount)
{
int valueSum = 0;
for (int i = 0; i < loopCount; i++)
{
valueSum = valueSum + ((this.firstValue + this.secondValue + this.thirdValue) * i);
}
return valueSum;
}
}

class Program
{
static void Main(string[] args)
{
ClassA classA = new ClassA(25);
classA.firstValue = 15;
classA.ThirdValue = 35;

Console.WriteLine(classA.ReturnValues());
Console.WriteLine(classA.ReturnValues(5));
}
}

Let’s assume we want to assign the secondValue field during an object creation.

public ClassA(int field01Value)
{
this.secondValue = field01Value;
}

The code above is a simple constructor that is executed during object creation. When we provide an argument then the secondValue field is assigned.

Now, we want to assign the thirdValue, but we don’t have access to it outside the class. Because it has a private modifier. We can implement a property.

public int ThirdValue
{
get
{
return thirdValue;
}
set
{
this.thirdValue = value;
}
}

We have access to a value through a method.

As you see below:

  • The firstValue is assigned directly (15),
  • The secondValue through the constructor during the object creation (25),
  • The thirdValue through the property (35).
ClassA classA = new ClassA(25);

classA.firstValue = 15;
classA.ThirdValue = 35;

Now, we would like to do some operations on the created object. In order to do this, we will make a method.

A method is something like a function inside a class. If you want to look at an example of the function. You can check this article out: C# functions — basics

public string ReturnValues()
{
this.firstValue = this.firstValue + 15;
string finalString = $"A first value: {this.firstValue}, a second value: {this.secondValue}, a third value: {this.thirdValue}.";
return finalString;
}

This particular method modifies the firstValue, concatenate all the values into a single string and returns a string text. It is invoked with this code:

Console.WriteLine(classA.ReturnValues());

Now, I would like to have a second method with the same name. It is possible and named as a method overloading. In the second method we need to provide a different input parameter set — with a different combination of types.

public int ReturnValues(int loopCount)
{
int valueSum = 0;
for (int i = 0; i < loopCount; i++)
{
valueSum = valueSum + ((this.firstValue + this.secondValue + this.thirdValue) * i);
}
return valueSum;
}

Let’s run the program.

The output is:

Here is the entire code on GitHub.

Now, let’s create a closer to a real-world example. In this post, we’ve been calling an MS Fabric REST API from a C# code: C# and Power BI REST API

We will put the code into a separate file as a class in the same namespace as the application.

using Azure.Identity;

namespace CsharpObjects
{
public class AzureCredentialFabric
{
private bool readMode;
private string tenantId;
private string clientId;
private string secret;
public string? token;

public AzureCredentialFabric(bool readmode, string tenantid, string clientid, string secret)
{
this.readMode = readmode;
this.tenantId = tenantid;
this.clientId = clientid;
this.secret = secret;
}
private HttpClient CreateClient()
{

if (readMode) // Type of a credential we want to use
{
var credential = new ClientSecretCredential(tenantId, clientId, secret); // A service principal
token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://analysis.windows.net/powerbi/api/.default" })).Token.ToString();
}
else
{ // Authenticate first: az login --scope https://graph.microsoft.com/.default --allow-no-subscriptions or use an Azure credential
var credential = new ChainedTokenCredential(new AzureCliCredential(), new DefaultAzureCredential());
token = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://analysis.windows.net/powerbi/api/.default" })).Token.ToString();
}

// An http client with enriched witch a Bearer token.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
return client;
}

public string GetWorkspaces(){
HttpClient client = CreateClient();
var workspacesResponse = client.GetStringAsync("https://api.powerbi.com/v1.0/myorg/groups");
return workspacesResponse.Result;
}
}
}

We have five fields, four of them are created during object creation. The GetWorkspaces method is public and will be used by the app directly. The CreateClient method is used by the GetWorkspaces method and marked as private. So, the application doesn’t have access to it directly.

Here we instantiate an object and get workspaces through the GetWorkspaces method.

AzureCredentialFabric acf = new AzureCredentialFabric(true, "3*****7", "e*****4", "Z*****J");
string workspaceList = acf.GetWorkspaces();
Console.WriteLine(workspaceList);

The code on GitHub.

--

--

Michal Molka
Michal Molka

Written by Michal Molka

Architect | Azure | Power BI | Fabric | Power Platform | Infrastructure | Security | M365

No responses yet