Skip to main content

Posts

Showing posts with the label dotnet

Best practice Generic List Filter using Func in C#

  In this Chapter we will learn about Func<x,y> delegate and its real time implementations and will see how we can create centralize functions to filter generic list. Basic Definition Func delegates offer a straightforward approach to defining and utilising methods by passing them as parameters and returning them as results. Func<>  is a delegate type for methods that return a value. we can have up to 16 parameters, with the return type always being the last type parameter. It’s useful for passing methods as arguments or working with lambda expressions in a clean and concise way. Syntax Consider below syntax, it has two parts left and right. Right side of lamba expression is return value and Left side of lamba expression is input parameters. Example:  This is simple code using System; class Program { static void Main () { // A Func delegate that adds two integers Func< int , int , int > add = (x, y) => x + y; int ...

Builder Pattern in C#: Practical Implementation and Examples

  This pattern can be ideal approach to create complex objects The Builder pattern is a creational design pattern that is used to construct complex objects step by step. It allows you to create different representations of an object using the same construction process. Let’s first understand the problems that exist without using this pattern. Complex Constructor with Many Parameters When creating objects that require many parameters, constructors can become lengthy and hard to read. public class House { public House ( int walls, int doors, int windows, bool hasGarage, bool hasSwimmingPool, bool hasStatues, bool hasGarden) { // Initialization } } There are many problems if constructor have too many parameters i) Each time we need to pass n numbers of parameters at time of object creations ii) we need to update constructor if we need to pass one more parameter so such constructor difficult to manage 2.  Constructor Overload Explosion Sometimes we ne...