C# — functions

Michal Molka
4 min readOct 25, 2024

Functions are blocks of code that we can encapsulate for further use. Instead of copying and pasting the same code over and over. We can use a function and reuse it in a more concise and handy way. Here are few examples:

A function can return a value or do some work and return nothing.

The first function returns a double typed number.

static double ReturnNumber(bool condition, double number01, double number02)
{
double finalNumber = 0;
if (condition)
{
finalNumber = number01 + 15;
}
else
{
finalNumber = number02 + 25;
}
return finalNumber;
}

double returnedNumber = ReturnNumber(false, 5.5, 8.5) + 55;
Console.WriteLine(returnedNumber);

Let’s disassembly the function. The ReturnNumber named function returns a double valued type. There are three input parameters: bool condition, double number01, double number02. A function definition checks the first parameter then assigns a proper value to a finalNumber variable then returns it.

In a program code, outside the function. The function is called and assigned to a returnedNumber double typed variable.

If you don’t want to return any value and make the function to do some work you can use a “void” modifier.

static void ReturnText(int choose, string sentencePart01, string sentencePart02)
{
string finalSentence;
switch (choose)
{
case 50:
finalSentence = $"A sentence part 01: {sentencePart01}, Sentence part 02: {sentencePart02}.";
break;
case 100:
finalSentence = $"A sentence part 01: {sentencePart02}, Sentence part 02: {sentencePart02}.";
break;
default:
finalSentence = "Only a sentence.";
break;
}
Console.WriteLine(finalSentence);
}

ReturnText(50, "Part01", "Part02");

The “void” parameter means that the function doesn’t return any value. And an above example indeed does it. When you call it. It concatenates two parameters depending on a condition. Then simply print the variable to a console.

You might wonder whether it is possible to put a function as another function parameter. The answer is yes. It is possible. There are two ways.

Let’s assume we have a list of numbers we want to iterate. Then make a calculation and return a sum of the numbers.

We will create a new function and reuse the previous ReturnNumber function.

List<double> list01 = new List<double>{155.5, 255.6, 355.7};

static double Functions01(Func<bool, double, double, double> function01, List<double> list01)
{
double value01 = 0;
foreach (double item in list01)
{
value01 = value01 + function01(true, item, 2.5);
}
return value01;
}

Console.WriteLine(Functions01(ReturnNumber, list01));

The ReturnNumber function is the first parameter of the Functions01 function. Func<bool, double, double, double> means that the ReturnNumber function input is bool, double, double and returns a double type (the last one).

There is a second way to do the same stuff. We can use delegates.

public delegate double FunctionDelegate(bool c, double n01, double n02);

List<double> list01 = new List<double>{155.5, 255.6, 355.7};

static double Functions02(FunctionDelegate function02, List<double> list01)
{
double value01 = 0;
foreach (double item in list01)
{
value01 = value01 + function02(true, item, 2.5);
}
return value01;
}

Console.WriteLine(Functions02(ReturnNumber, list01));

Firstly, we create a delegate named FunctionDelegate. Then place the delegate as a parameter of the function.

Here is an output of four previous functions:

Now, we create 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

In order to create an authentication token and obtain an Http client we placed the code inside an application. This is a good candidate to put it in a function and reuse depending on our needs.

static HttpClient AzureCredentialFabric(bool readMode, string tenantId, string clientId, string secret)
{
string token;

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;

}

HttpClient client = AzureCredentialFabric(true, "3*****7", "e*****4", "Z*****J");

// A call to an MS Fabric REST API
var workspacesResponse = client.GetStringAsync("https://api.powerbi.com/v1.0/myorg/groups");
Console.WriteLine(workspacesResponse.Result);

And here is the code on GitHub.

If you want to look how to work with object then feel more than welcome in here: C# — objects. C# is an object oriented programming… | by Michal Molka | Nov, 2024 | Medium

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Michal Molka
Michal Molka

Written by Michal Molka

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

No responses yet

Write a response