Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CM-1038: Passing by Value vs Passing by Reference in C# #1972

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PassingByValueVsPassingByReference", "PassingByValueVsPassingByReference\PassingByValueVsPassingByReference.csproj", "{EF79444D-68B3-452E-9D96-4F247A01F37A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PassingByValueVsPassingByReference.Test", "PassingByValueVsPassingByReference.Test\PassingByValueVsPassingByReference.Test.csproj", "{7223F912-2689-44D6-8C1A-273E2A416474}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F998CE9A-46AA-4F76-A345-1CDBEE641238}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F998CE9A-46AA-4F76-A345-1CDBEE641238}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F998CE9A-46AA-4F76-A345-1CDBEE641238}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F998CE9A-46AA-4F76-A345-1CDBEE641238}.Release|Any CPU.Build.0 = Release|Any CPU
{7D0B0F80-A937-4112-9B59-08ED07E3EE6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D0B0F80-A937-4112-9B59-08ED07E3EE6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D0B0F80-A937-4112-9B59-08ED07E3EE6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D0B0F80-A937-4112-9B59-08ED07E3EE6A}.Release|Any CPU.Build.0 = Release|Any CPU
{EF79444D-68B3-452E-9D96-4F247A01F37A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EF79444D-68B3-452E-9D96-4F247A01F37A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EF79444D-68B3-452E-9D96-4F247A01F37A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EF79444D-68B3-452E-9D96-4F247A01F37A}.Release|Any CPU.Build.0 = Release|Any CPU
{7223F912-2689-44D6-8C1A-273E2A416474}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7223F912-2689-44D6-8C1A-273E2A416474}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7223F912-2689-44D6-8C1A-273E2A416474}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7223F912-2689-44D6-8C1A-273E2A416474}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {66477A14-615C-41E7-B70A-D95593B09965}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.0.4" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.4" />
<PackageReference Include="coverlet.collector" Version="6.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\PassingByValueVsPassingByReference\PassingByValueVsPassingByReference.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace PassingByValueVsPassingByReference.Test
{
[TestClass]
public class PassingByReferenceVsPassByValueUnitTest
{
[TestMethod]
public void GivenDoubleNumber_WhenPassedToUpdatePriceByPercentMethod_ThenNoChangeWillAffectTheNumber()
{
// Given
double number = 30;
int discountRate = 50;

// When
Program.UpdatePriceByPercent(number, discountRate);

//Assert
Assert.AreEqual(number, 30);
}

[TestMethod]
public void GivenDoubleNumber_WhenPassedToUpdatePriceByPercentByRefMethod_ThenWillChangeTheNumberValue()
{
// Given
double number = 30;
int discountRate = 50;

// When
Program.UpdatePriceByPercentByRef(ref number, discountRate);

//Assert
Assert.AreEqual(number, 15);
}

[TestMethod]
public void GivenProductObject_WhenPassedToApplyDiscountMethod_ThenWillChangeThePrice()
{
// Given
var product = new Product
{
ProductId = 1,
Price = 60,
Cost = 10
};

int discountRate = 50;

// When
Program.ApplyDiscount(product, discountRate);

//Assert
Assert.AreEqual(product.Price, 30);
}

[TestMethod]
public void GivenArrayOfDoubleNumbers_WhenPassedToUpdatePricesByPercentMethod_ThenWillChangeEveryItemInIt()
{
// Given
double[] originalPrices = [30, 15, 21.5, 50];
double[] prices = [.. originalPrices];

int discountRate = -50;

// When
Program.UpdatePricesByPercent(prices, discountRate);

//Assert
for (int i = 0; i < originalPrices.Length; i++)
{
Assert.AreEqual(prices[i], originalPrices[i] * (1 + discountRate / 100.0));
}
}

[TestMethod]
public void GivenAnUnassignedDoubleVariable_WhenPassedToMakeItZeroMethod_ThenWillHaveZero()
{
// Given
double zero;

// When
Program.MakeItZero(out zero);

//Assert
Assert.AreEqual(zero, 0);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
namespace PassingByValueVsPassingByReference;

public class Program
{
public static void Main()
{
int discountRate = 50;
double productAPrice = 60;

double zero;

var product = new Product
{
ProductId = 1,
Price = 60,
Cost = 10
};

ApplyDiscount(product, 50);
Console.WriteLine($"{nameof(product)}: {product.Price}");

Console.WriteLine("Initial");
Console.WriteLine($"{nameof(productAPrice)}: {productAPrice}");

UpdatePriceByPercent(productAPrice, discountRate);
Console.WriteLine("After passing by value");
Console.WriteLine($"{nameof(productAPrice)}: {productAPrice}");

UpdatePriceByPercentByRef(ref productAPrice, discountRate);
Console.WriteLine("After passing by ref");
Console.WriteLine($"{nameof(productAPrice)}: {productAPrice}");

double productANewPrice = CalculateDiscount(productAPrice, discountRate);
Console.WriteLine($"{nameof(productANewPrice)}: {productANewPrice}");

double[] prices = [30, 15, 21.5, 50];
UpdatePricesByPercent(prices, -10);

MakeItZero(out zero);
Console.WriteLine($"{nameof(zero)}: {zero}");
}

public static void UpdatePricesByPercent(double[] prices, int rate)
{
for (int i = 0; i < prices.Length; i++)
{
prices[i] += prices[i] * rate / 100;
}
}

public static double CalculateDiscount(double price, int discountRate)
{
return price - price * discountRate / 100;
}

public static void UpdatePriceByPercent(double price, int discountRate)
{
price = price - price * discountRate / 100;
}

public static void UpdatePriceByPercentByRef(ref double price, int discountRate)
{
price -= price * discountRate / 100;
}

public static void ApplyDiscount(Product product, int discountRate)
{
product.Price -= product.Price * discountRate / 100;
}

public static void MakeItZero(out double price)
{
price = 0;
}
}

public class Product
{
public int ProductId { get; set; }
public double Price { get; set; }
public double Cost { get; set; }
}
4 changes: 4 additions & 0 deletions csharp-methods/PassingByValueVsPassingByReference/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Passing By Value vs Passing By Reference in C#

This repository contains the source code for the "Passing By Value vs Passing By Reference in C#" of articles on Code Maze