nameof expression (C# reference)

nameof expression produces the name of a variable, type, or member as the string constant. A nameof expression is evaluated at compile time and has no effect at run time. When the operand is a type or a namespace, the produced name isn’t fully qualified. The following example shows the use of a nameof expression:

Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add

List<int> numbers = [1, 2, 3];
Console.WriteLine(nameof(numbers));  // output: numbers
Console.WriteLine(nameof(numbers.Count));  // output: Count
Console.WriteLine(nameof(numbers.Add));  // output: Add

Read more here

How to clone c# list?

Shallow Copy

We can easily achieve a shallow copy of our pizzas list with any of the methods from the previous section. But a shallow copy of a List<T>, where T is a reference type, copies only the structure of the collection and references to its elements, not the elements themselves. This means that changes to the elements in any of the two lists will be reflected in both the original and copied lists.

Let’s illustrate this:

var clonedPizzas = pizzas.ToList();

var margherita = pizzas
    .FirstOrDefault(x => x.Name == "Margherita");

margherita.Toppings.Clear();

First, we create a clonedPizzas variable and clone the contents of pizzas to it using the ToList method (using any of the other methods used earlier will produce the same result). Then we get the Margherita pizza from the original list using the FirstOrDefault method. Finally, we use the Clear method to empty the list of Toppings for that pizza.

Now, let’s see what happens:

Console.WriteLine($"Original Margherita: {pizzas.First()}");
Console.WriteLine($"Cloned with ToList: {clonedPizzas.First()}");

We print the first pizza of each list to the console, which in both cases is the Margherita, using the First method.

We overrode the ToString method which will give us an easy-to-read representation of each pizza. Now, we can check the result:

Original Margherita: Pizza name: Margherita; Toppings:
Cloned with ToList: Pizza name: Margherita; Toppings:

We can see that both the original and copied Margherita pizzas now have an empty list of Toppings. This is because when creating a shallow copy, we only clone the references to the objects, not the actual objects. This is not ideal because when we change elements in one list, we change the elements everywhere we have copied that list.

This might cause serious problems for us, so let’s what we can do to prevent it. Read more here.

Using TransactionScope multiple times

Ignore anything about object structure or responsibilities for persistence. This is an example to help me understand how I should be doing things. Partly because it seems not to work when I try and replace oracle with SqlLite as the db provider factory, and I’m wondering where I should spend time investigating.

Let’s begin with an example;

public class ThingPart
{
    private DbProviderFactory connectionFactory;

    public void SavePart()
    {
        using (TransactionScope ts = new TransactionScope()
        {
            ///save the bits I want to be done in a single transaction
            SavePartA();
            SavePartB();
            ts.Complete(); 
        }
    }

    private void SavePartA()
    {
        using (Connection con = connectionFactory.CreateConnection()
        {
            con.Open();
            Command command = con.CreateCommand();
            ...
            command.ExecuteNonQuery();             
        }
    }

    private void SavePartB()
    {
        using (Connection con = connectionFactory.CreateConnection()
        {
            con.Open();
            Command command = con.CreateCommand();
            ...
            command.ExecuteNonQuery();             
        }
    }
}

And something which represents the Thing:

public class Thing
{
    private DbProviderFactory connectionFactory;

    public void SaveThing()
    {
        using (TransactionScope ts = new TransactionScope()
        {
            ///save the bits I want to be done in a single transaction
            SaveHeader();
            foreach (ThingPart part in parts)
            {
                part.SavePart();
            }  
            ts.Complete();    
        }
    }

    private void SaveHeader()
    {
        using (Connection con = connectionFactory.CreateConnection()
        {
            con.Open();
            Command command = con.CreateCommand();
            ...
            command.ExecuteNonQuery();             
        }
    }
}

I also have something which manages many things.

public class ThingManager
{    
    public void SaveThings
    {        
        using (TransactionScope ts = new TransactionScope)
        {            
            foreach (Thing thing in things)
            {
                thing.SaveThing();
            }            
        }        
    }    
}

Its my understanding that:

The connections will not be new and will be reused from the pool each time (assuming DbProvider supports connection pooling and it is enabled)

This depends – e.g. the SAME connection will be reused for successive steps in your aggregate transaction if all connections are to the same DB, with the same credentials, and if SQL is able to use the Lightweight transaction manager (SQL 2005 and later). (but SQL Connection pooling still works if that was what you were asking?)


The transactions will be such that if I just called ThingPart.SavePart (from outside the context of any other class) then part A and B would either both be saved or neither would be.

Atomic SavePart – yes, this will work ACID as expected.


If I call Thing.Save (from outside the context of any other class) then the Header and all the parts will be all saved or non will be, ie everything will happen in the same transaction

Yes nesting TransactionScopes with the same scope will also be atomic. Transaction will only commit when the outermost TS is Completed.


If I call ThingManager.SaveThings then all my things will be saved or none will be, ie everything will happen in the same transaction.

Yes , also atomic, but note that you will be escalating SQL locks. If it makes sense to commit each Thing (and its ThingParts) individually, this would be preferable from a SQL concurrency point of view.


If I change the DbProviderFactory implementation that is used, it shouldn’t make a difference.

The Provider will need to be compatable as a TransactionScope resource manager (and probably DTC Compliant as well). e.g. don’t move your database to Rocket U2 and expect TransactionScopes to work.

Just one gotcha – new TransactionScope() defaults to isolation level READ_SERIALIZABLE – this is often over pessimistic for most scenarios – READ COMMITTED is usually more applicable.

Reference

https://stackoverflow.com/questions/7553971/using-transactionscope-multiple-times

Base class implementing interface

Let’s think it this way;

public interface IBreathing
{
    void Breathe();
}

//because every human breathe
public abstract class Human : IBreathing
{
    abstract void Breathe();
}

public interface IVillain
{
    void FightHumanity();
}

public interface IHero
{
    void SaveHumanity();
}

//not every human is a villain
public class HumanVillain : Human, IVillain
{
    void Breathe() {}
    void FightHumanity() {}
}

//but not every human is a hero either
public class HumanHero : Human, IHero
{
    void Breathe() {}
    void SaveHumanity() {}
}

The point is that the base class should implement interface (or inherit but only expose its definition as abstract) only if every other class that derives from it should also implement that interface. So, with basic example provided above, you’d make Human implement IBreathing only if every Human breaths (which is correct here).

But! You can’t make Human implement both IVillain and IHero because that would make us unable to distinguish later on if it’s one or another. Actually, such implementation would imply that every Human is both a villain and hero at once.

Conclusion

  1. There are no risks of base class implementing an interface, if every class deriving from it should implement that interface too.
  2. It is always better to implement an interface on the sub-class, If every class deriving from base should also implement that interface, it’s rather a must
  3. If every class deriving from base one should implement such interface, make base class inherit it. If not, make concrete class implement such interface.

Reading XmlDocument fragment

I would like to loop through following collection of authors and for each author  retrieve its first and last name and put them in a variable strFirst and  strLast?

<Authors>  
  <Author>  
    <FirstName>Jon</FirstName>  
    <LastName>Doe</LastName>  
  </Author>  
  <Author>  
    <FirstName>Shahzad</FirstName>  
    <LastName>Khan</LastName>  
  </Author>  
</Authors>  

We’ll use XmlDocument class to parse this XML fragment;

using System;    
using System.Xml;    
public class XMLApp    
{    
    public void YourMethod(String strFirst, String strLast)    
    {    
        // Do something with strFirst and strLast.    
        // ...    
        Console.WriteLine("{0}, {1}", strLast, strFirst);    
    }    
    public void ProcessXML(String xmlText)    
    {    
        XmlDocument _doc = new XmlDocument();    
        _doc.LoadXml(xmlText);    
        // alternately, _doc.Load( _strFilename); to read from a file.    
        XmlNodeList _fnames = _doc.GetElementsByTagName("FirstName");    
        XmlNodeList _lnames = _doc.GetElementsByTagName("LastName");    
        // I'm assuming every FirstName has a LastName in this example, your requirements may vary. //     
        for (int _i = 0; _i < _fnames.Count; ++_i)    
        {    
            YourMethod(_fnames[_i].InnerText,    
            _lnames[_i].InnerText);    
        }    
        public static void Main(String[] args)    
        {    
            XMLApp _app = new XMLApp();    
            // Passing XML text as a String, you can also use the    
            // XMLDocument::Load( ) method to read the XML from a file.    
            //    
            _app.ProcessXML(@" <Authors>    
            <Author>    
              <FirstName>John</FirstName>    
              <LastName>Doe</LastName>    
            </Author>    
            <Author>    
              <FirstName>Shahzad</FirstName>    
              <LastName>Khan</LastName>    
            </Author>    
            </Authors> ");    
        }    
    }// end XMLApp    
}  

Resources

https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmldocument?view=net-7.0