course link here

 .-.
(o o)
| O |
|   |
'~~~'

contructor overloading and this:

Just like other methods, constructors can be overloaded. For example, we may want to define an additional constructor that takes one argument:

public Forest(int area, string country)
{ 
  this.Area = area;
  this.Country = country;
 }
 
public Forest(int area)
{ 
  this.Area = area;
  this.Country = "Unknown";
}

The first constructor provides values for both fields, and the second gives a default value when the country is not provided. Now you can create a Forest instance in two ways:

Forest f = new Forest(800, "Africa");
Forest f2 = new Forest(400);

Notice how we’ve written duplicate code for our second constructor: this.Area = area;. Later on, if we need to adjust the constructor, we’ll need to find every copy of the code and make the exact same change. That means more work and chances for errors.

We have two options to resolve this. In either case we will remove the duplicated code:

  1. Use default arguments. This is useful if you are using C# 4.0 or later (which is fairly common) and the only difference between constructors is default values.
    public Forest(int area, string country = "Unknown")
    {
      this.Area = area;
      this.Country = country;
    }

    2. Use : this(), which refers to another constructor in the same class. This is useful for old C# programs (before 4.0) and when your second constructor has additional functionality. This example has an additional functionality of announcing the default value.

    public Forest(int area, string country)
    { 
      this.Area = area;
      this.Country = country;
    }
     
    public Forest(int area) : this(area, "Unknown")
    { 
      Console.WriteLine("Country property not specified. Value defaulted to 'Unknown'.");
    }

    Remember that this.Area refers to the current instance of a class. When we use this() like a method, it refers to another constructor in the current class. In this example, the second constructor calls this() — which refers to the first Forest() constructor — AND it prints information to the console.

Casting

So far we’ve referred to objects with a reference of their own type, an inherited type, or an implemented interface:

Dissertation diss = new Dissertation();
Book bdiss = diss;
IFlippable fdiss = diss;

The process is called upcasting. As we saw in the last exercise upcasting allows us to work with multiple types at once. It also lets us safely store an object without knowing its specific type. You can think of upcasting as using a reference “up” the inheritance hierarchy:

What happens if you try to downcast, or reference an object by a subclass? You’ll need to do this when you want to access the specific functionality of a subclass.

For example what happens when we refer to a Book object as a Dissertation type?

Book bk = new Book();
Dissertation dbk = bk;
// Error!

The code produces this error:

error CS0266: Cannot implicitly convert type `Book` to `Dissertation`. An explicit conversion exists (are you missing a cast?)

Not every downcast is possible in C#. In this case, Dissertation has a Define() method that is incompatible with Book. This is the computer’s way of telling you: there’s a chance that this cast won’t work!

To get around this error, we must explicitly downcast, like below. The desired type is written in parentheses:

Book bk = new Book();
Dissertation bdk = (Dissertation)bk;

This essentially tells the computer: “I know the risk I’m taking, and this might fail if I’m not careful.”

In many cases, the downcast will still fail. Here, the Dissertation type reference bdk can’t reference a Book object, so when we explicitly downcast we see that it fails with a new error message:

System.InvalidCastException: Specified cast is not valid.

There are multiple ways to deal with downcasting, including the as and is operators. We won’t get into those now, but you can learn about them in the Microsoft C# Programming Guide: Casting and type conversions if you’d like. For now, focus on these things:

  • Upcasting is creating a superclass or interface reference from a subclass reference
  • Downcasting is creating a subclass reference from a superclass or interface reference.
  • Upcasting can be done implicitly, while downcasting cannot

So far we’ve seen:

  • A reference to an object
  • Multiple references to an object

What about a reference that refers to no object? In C# a reference to no object is called either a null reference or unassigned. We’ll need to apply these concepts in C# whenever we want to show that a reference is “missing”, create a reference variable without defining it, or initialize an empty array.

In the first use case, we’d like to create a reference that is “missing” or empty. We set it equal to the keyword null:

Diary dy = null;

In the second case, if we create a reference variable without a value, it is unassigned:

Diary dy;
// dy is unassigned

In the third case, if we create an empty array of reference types, each element is an unassigned reference:

Diary[] diaries = new Diary[5];
// diaries[1] is unassigned, diaries[2] is unassigned, etc.

Be careful when checking for null and unassigned references. We can only compare a null reference if it is explicitly labeled null:

Diary dy = null;
Console.WriteLine(dy == null);
// Output: true

For the other two cases, comparing an unassigned variable we’ll get an error:

Object o;
Console.WriteLine (o == null);
// error CS0165: Use of unassigned local variable 'o'

This might seem annoying at first, but it’s actually a good thing: the C# compiler prevents future issues down the road by raising an error the first time an unassigned variable is used.

Arrays of References

We know that we can use inherited classes and implemented interfaces to reference an object:

Dissertation diss = new Dissertation(50);
IFlippable fdiss = diss;

This allows to work with many similar types at the same time. Imagine if we didn’t have this feature and we had to “flip” a group of Diary and Dissertation types:

Diary dy1 = new Diary(1);
Diary dy2 = new Diary(30);
Dissertation diss1 = new Dissertation(50);
Dissertation diss2 = new Dissertation(49);
dy1.Flip();
dy2.Flip();
diss1.Flip();
diss2.Flip();

Look at all that code! It would be faster and safer if we could store the references in an array and loop through it. But would it be an array of Diary[] or an array of Dissertation[] or something else? Since both dissertations and diaries are flippable (they both implement the IFlippable interface), we can create references to them as IFlippables:

IFlippable f1 = new Diary(1);
IFlippable f2 = new Diary(30);
IFlippable f3 = new Dissertation(50);
IFlippable f4 = new Dissertation(49);

Instead of dealing with individual variables, we can use an array of IFlippable references:

IFlippable[] classroom = new IFlippable[] { new Diary(1), new Diary(30), new Dissertation(50), new Dissertation(49) };

Then to “flip” each element, we can write a foreach loop:

foreach (IFlippable f in classroom) 
{
  f.Flip();
}

We can only access the functionality defined in the interface. For example, we couldn’t access f.Title because Title isn’t a property defined in IFlippable.

LISTS

A list is a sequential data structure that can hold any type. Like arrays, you can use them to store any sequential information, like the letters of the alphabet, comments on a blogpost, the finishing times for a horse race, or items on a restaurant menu.

You create a list using the new keyword, like you would create any other class. You specify the type of element inside angle brackets: < >. In this example, the list is named citiesList and it holds instances of the type string.

List<string> citiesList = new List<string>(); // or: 
Dictionary<string, double> PizzaCost = new Dictionary<string, double>()
      {
        { "Cheese", 10.00 },
        { "Pepperoni", 11.00 },
        { "Vegetarian", 12.00 },
      };

 

You can add elements to the list using the Add() method:

citiesList.Add("Delhi");

You can access elements using indices and square brackets:

string city = citiesList[0];

You can also re-assign elements using bracket notation:

citiesList[0] = "New Delhi";

In order to use lists, you’ll need to add this to the top of your file. We’ll explain this in detail later:

using System.Collections.Generic;

Our first way to create lists and add items took multiple lines:

List<string> citiesList = new List<string>();
citiesList.Add("Delhi");
citiesList.Add("Los Angeles");

We can do it all in one line using object initialization:

List<string> citiesList2 = new List<string> { "Delhi", "Los Angeles" };
or:
  List<string> namesnew List<string>()
  {
    "Scott Allen",
    "James Dorf",
    "Tim Alston",
    "Jane Rashid",
    "John Doe"
  };

We won’t cover everything about object initialization in this lesson, but you do need to recognize and use it.

  • Basic construction uses parentheses ( ) and no values.
  • Object initialization uses curly braces { } and the actual values go in-between.

If we need to add elements to that second list later, we can still use Add():

citiesList2.Add("Kiev");

We can check on the status of our list in two ways.

We can find the number of elements in the list using the Count property:

List<string> citiesList = new List<string> { "Delhi", "Los Angeles" };
int numberCities = citiesList.Count;
// numberCities is 2

We can check if an element exists in a list using the Contains() method:

bool hasDelhi = citiesList.Contains("Delhi");
bool hasDubai = citiesList.Contains("Dubai");
// hasDelhi is true, hasDubai is false

To remove a specific item from a list we use the Remove() method. It expects the specific item as an argument and it returns true if it was successfully removed. This code removes "Delhi" from the list and returns true:

List<string> citiesList = new List<string> { "Delhi", "Los Angeles", "Kiev" };
bool success = citiesList.Remove("Delhi");
// success is true

If the specific item does NOT exist in the list, the method call returns false. Since "Dubai" isn’t in the list, success will be false:

success = citiesList.Remove("Dubai");
// success is false

If you remove an element in the middle of the list, all of the elements will be “shifted” down one index. In the first example, the list was originally:

[ “Delhi”, “Los Angeles”, “Kiev” ]

After the call to Remove("Delhi"), the list becomes

[ "Los Angeles", "Kiev" ]

clearing

If we need to remove all of the elements from a list, we could iterate through the entire list and call Remove(). The easier way is to use the Clear() method.

List<string> citiesList = new List<string> { "Delhi", "Los Angeles", "Kiev" };
citiesList.Clear();
 
Console.WriteLine(citiesList.Count);
// Output: 0

Working with Ranges

List<string> places = new List<string> { "first", "second" };
 
places.AddRange(new string[] { "fifth", "sixth" });
// List is  "first", "second", "fifth", "sixth" ]
places.InsertRange(2, new string[] { "third", "fourth"});
// List is [ "first", "second", "third", "fourth", "fifth", "sixth" ]
places.RemoveRange(4, 2);
// List is [ "first", "second", "third", "fourth" ]
List<string> newPlaces = places.GetRange(0, 3);
// New list is [ "first", "second", "third" ]

for (int i = 0; i < numbers.Count; i++)
{
   Console.WriteLine(numbers[i]);
}

//or

foreach (int number in numbers)
{
   Console.WriteLine(number);
}

You’ve done great with lists so far! It’s time to take a look at the bigger picture.

Remember the one line we mentioned at the beginning of this lesson?

using System.Collections.Generic;

The list class is in a group of classes called generic collections. They don’t exist in the default set of System classes, so we need to make a reference to them with this line.

Generic collections are data structures that are defined with a generic type. Each class is defined generally without a specific type in mind. When we make an actual instance, we define the specific type:

List<string> citiesList = new List<string>();
List<Object> objects = new List<Object>();

Imagine it like a set of general instructions: in a toy store, we can tell the employees how to add and remove items from a shelf without specifying the type of toy. In the same way, we can use Add() and Remove() without knowing a lists’s data type.

For this reason, the formal class name of lists is List<T>. That T is a type parameter: it represents some type that we can specify later. The general instructions, however are neatly contained in the generic List<T> class.

Let’s see why this is useful by imagining the other, more difficult ways we could create “generic” collections:

  • Use type-specific classes, like StringListIntList, etc. — We would have to make a list class for EVERY type, defining the same properties and methods for each list class.
  • Use a list containing Object types, List<Object> — Using Object means we can’t use any of the unique functionality of each type and it takes a lot of computing power to convert references to and from the Object type.

As you continue coding, you’ll see for yourself how useful generic collections are!

simple words: LINQ is a set of Language and framework features fro querying collections

Imagine you’re building a new game in C#, with dozens of characters to manage in your database. How would you access them all? What if you need to apply a filter? What if you needed to format each character name?

You might think of storing characters in a list and running through each element with a foreach loop. You’d have to write nested if statements, re-format each element, and store each result in a new list.

The result isn’t pretty.

Suppose that we want to find all the names in a list which are longer than 6 letters and return them in all uppercase letters. You can see what it would look like in Program.cs in the code editor.

And remember that this only works in a running C# file. What if the database was stored in a separate server somewhere and it was implemented with SQL instead of C#?

The solution is LINQ. It works for complex selections and transformations, and it works on local and remote data sources. Each selection/transformation is called a query, and LINQ gives us new syntax and methods to write them.

Imagine LINQ like an add-on to C# and .NET. Once you import the LINQ features, you can write new syntax, like:

string[] names = { "Tiana", "Dwayne", "Helena" };
var filteredNames = from n in names
  where n.Contains("a")
  select n;

And you can use new methods on collections, like Where():

var shortNames = names.Where(n => n.Length < 4);

In this lesson you’ll learn :

  • How to import the LINQ features to C#
  • How to run LINQ queries on datasets
  • How to identify method and query syntax
  • Basic operators, such as SelectWhere, and from

Before we jump into the syntax and methods, let’s import the features into our code. To use LINQ in a file, add this line to the top:

using System.Linq;

Often times we use LINQ with generic collections (like lists), so you may see both namespaces imported into a file:

using System.Collections.Generic;
using System.Linq;

Every LINQ query returns either a single value or an object of type IEnumerable<T>. For now, all you need to know about that second type is that:

  • It works with foreach loops, just like arrays and lists
  • You can check its length with Count()

Since the single value type and/or the parameter type T is not always known, it’s common to store a query’s returned value in a variable of type var.

var is just an implicitly typed variable — we let the C# compiler determine the actual type for us. Here’s one example:

string[] names = { "Tiana", "Dwayne", "Helena" };
var shortNames = names.Where(n => n.Length < 4);

In this case shortNames is actually of type IEnumerable<string>, but we don’t need to worry ourselves about that as long as we have var!

List<int> numbers = new List<int> { 3, 6, 9, 17, 21 };
 
Console.WriteLine(numbers.Count); //Lists use the property Count.
 
var triplets = numbers.Where(x => x % 3 == 0);
 
Console.WriteLine(triplets.Count()); // LINQ results (IEnumerable<T>) use the method Count().

 

In LINQ, you can write queries in two ways: in query syntax and method syntax.

Query syntax looks like a multi-line sentence. If you’ve used SQL, you might see some similarities:

var longLoudHeroes = from h in heroes
  where h.Length > 6
  select h.ToUpper();

Method syntax looks like plain old C#. We make method calls on the collection we are querying:

var longHeroes = heroes.Where(h => h.Length > 6);
var longLoudHeroes = longHeroes.Select(h => h.ToUpper());

In LINQ, we see where/Where() and select/Select() show up as both keywords and method calls. To cover both cases, they’re generally called operators.

Every developer has a personal preference between syntaxes, but you should be able to read both. In this lesson we’ll start with query syntax then move on to method.

A basic LINQ query, in query syntax, has three parts:

string[] heroes = { "D. Va", "Lucio", "Mercy", "Soldier 76", "Pharah", "Reinhardt" };
 
var shortHeroes = from h in heroes
  where h.Length < 8
  select h;
  • The from operator declares a variable to iterate through the sequence. In this case, h is used to iterate through heroes.
  • The where operator picks elements from the sequence if they satisfy the given condition. The condition is normally written like the conditional expressions you would find in an if statement. In this case, the condition is h.Length < 8.
  • The select operator determines what is returned for each element in the sequence. In this case, it’s just the element itself.

The from and select operators are required, where is optional. In this next example, select is used to make a new string starting with “Hero: “ for each element:

var heroTitles = from hero in heroes
  select $"HERO: {hero.ToUpper()}; // or e.g.: x => x.ToUpperCase()...

Each element in heroTitles would look like "HERO: D. VA""HERO: LUCIO", etc.

In method syntax, each query operator is written as a regular method call.

In the last exercise we selected every element with a length under 8. Here it is in method syntax:

string[] heroes = { "D. Va", "Lucio", "Mercy", "Soldier 76", "Pharah", "Reinhardt" };
var shortHeroes = heroes.Where(h => h.Length < 8);

The where operator is written as the method Where(), which takes a lambda expression as an argument. Remember that lambda expressions are a quick way to write a method. In this case, the method returns true if h is less than 8 characters long.

Where() calls this lambda expression for every element in heroes. If it returns true, then the element is added to the resulting collection.

For example, the shortHeroes sequence from above would be:

[ D. Va, Lucio, Mercy, Pharah ]

Basic Method Syntax: Select

To transform each element in a sequence — like writing them in uppercase — we can use the select operator. In method syntax it’s written as the method Select(), which takes a lambda expression:

string[] heroes = { "D. Va", "Lucio", "Mercy", "Soldier 76", "Pharah", "Reinhardt" };
var loudHeroes = heroes.Select(h => h.ToUpper());

We can combine Select() with Where() in two ways:

  1. Use separate statements:
    var longHeroes = heroes.Where(h => h.Length > 6);
    var longLoudHeroes = longHeroes.Select(h => h.ToUpper());
    

     

  2. Chain the expressions:
    var longLoudHeroes = heroes
    .Where(h => h.Length > 6)
    .Select(h => h.ToUpper());
    

     

As with most of LINQ, the choice is up to you!

In the first option, we use two variable names and two statements. You can tell there are two separate statements by counting the semi-colons.

In the second option, we use one variable name and one statement.

If we must use method-syntax, we prefer the second option (chaining) because it is easier to read and write. You can imagine each line like a step in a conveyor belt, filtering and transforming the sequence as it goes.

So far you’ve seen query syntax and two flavors of method syntax.

/ Query syntax
var longLoudheroes = from h in heroes
  where h.Length > 6
  select h.ToUpper();
 
// Method syntax - separate statements
var longHeroes = heroes.Where(h => h.Length > 6);
var longLoudHeroes = longHeroes.Select(h => h.ToUpper());
 
// Method syntax - chained expressions
var longLoudHeroes2 = heroes
  .Where(h => h.Length > 6)
  .Select(h => h.ToUpper());

As you get into more advanced LINQ queries and learn new operators, you’ll get a feel for what works best in each situation. For now, we generally follow these rules:

  1. For single operator queries, use method syntax.
  2. For everything else, use query syntax.

 You’ve mostly seen LINQ used with arrays, but it can be used for lists as well! The syntax is the same:
List<string> heroesList = new List<string> { "D. Va", "Lucio", "Soldier 76" };
 
var longLoudheroes = from h in heroesList
  where h.Length > 6
  select h.ToUpper();
 
// longLoudHeroes is [ "SOLDIER 76" ]

Technically, LINQ can be used with any type that supports foreach loops, but we won’t cover all of those here.

All C# expressions are preceded with the character “@“. For example:

<h1>@DateTime.Now.ToShortDateString()</h1>

If your C# code needs spaces, then it must be wrapped in parentheses:

<p>Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))</p>

We can use code blocks:

@{ // C# code }

if our code exceeds one line or we want to declare variables.

@{
  int num1 = 6;
  int num2 = 4;
  int result = num1 + num2;
}

<h3> The result of @num1 + @num2 is: @result</h3>

Result:

<h3> The result of 6 + 4 is: 10</h3>



Conditionals in Razor Pages: If Statements

@if (value % 2 == 0)
{
  <p>The value was even.</p>
}
else if (value >= 1337)
{
  <p>The value is large.</p>
}
else
{
  <p>The value is odd and small.</p>
}
@{ int number = 2 }
 
@switch (number)
{
  case 1: <h1>The value is 1!</h1>
  break;
  case 2: <h1>The value is 2!</h1>
  break;
  default: ...
}
<ul>
  @for (int i = 0; i < names.Count; i++)
  {
    <li>@names[i]</li>
  }
</ul>

// Resulting HTML from the above example:

<ul>
  <li>Scott Allen</li>
  <li>James Dorf</li>
  <li>Tim Alston</li>
  <li>Jane Rashid</li>
  <li>John Doe</li>
</ul>

// ----

<ul>
  @foreach(string name in names)
  {
    <li>@name</li>
  }
</ul>

// Resulting HTML from the above example:

<ul>
  <li>Scott Allen</li>
  <li>James Dorf</li>
  <li>Tim Alston</li>
  <li>Jane Rashid</li>
  <li>John Doe</li>
</ul>

// ----

<ul>
  @{ 
    int counter = 0;
  }
  @while(counter < names.Count)
  {
    <li>@names[counter++]</li>
  }
</ul>

Resulting HTML from the above example:

<ul>
  <li>Scott Allen</li>
  <li>James Dorf</li>
  <li>Tim Alston</li>
  <li>Jane Rashid</li>
  <li>John Doe</li>
</ul>
// ViewData allows us to pass information from the page model into the view page. ViewData is of type ViewDataDictionary
public class IndexModel : PageModel
{
  public void OnGet()
  {
    ViewData["MyDogsName"] = "Alfie";
    ViewData["MyDogsAge"] = 7;
  }
}

@page
@model RazorTest.Pages.ExampleModel
<div>
  <p>My dog @ViewData["MyDogsName"] is @ViewData["MyDogsAge"] years old</p>
...
</div>

Most web apps have a common layout that provides the user with a consistent experience as they navigate from page to page. Certain layouts may include a header, footer, menus, and so on, that may be shared amongst different pages.

Let’s say we’re building an application that contains a header throughout most (if not all) of your pages. If we’re creating the markup for all these pages, the header will still need to be added to each one. That’s a lot of copy-pasting if the header does not change. We can avoid redundancy by essentially storing the header somewhere separate and rendering its content on each page. If our website needs an update we can simply change a single file and the changes will be reflected everywhere the content has been inserted.

Standard practice is to specify the location of the main layout page in the _ViewStart.cshtml file. This file is automatically generated under /Pages when we create a template with ASP.NET and it looks like this:

@{
    Layout = "_Layout";
}

Here, we’re directing our app to use the _Layout file as the main layout for all of our content. But where is _Layout coming from? Well, Razor Pages searches by walking up the directory tree from the location of the calling page looking for the filename specified, followed by the /Pages/Shared folder. In this case, our generated template has a _Layout.cshtml file under /Pages/Shared.

Once we specify the location of the layout page, that layout will affect all content pages. You can think of this layout as the main layout that’s used throughout your whole application.

By convention, layout pages use a leading underscore in their filename: _Layout.cshtml.

In the generated Razor Pages template the _Layout.cshtml file will contain a method call, @RenderBody() within the <body> tags:

<div class="container">
    <main role="main" class="pb-3">
        @RenderBody()
    </main>
</div>

When we work on our own view pages, the content will be rendered wherever @RenderBody() is being called on the layout page.

One other advantage of sharing pages this way is that we can use our handy ViewData dictionary and pass data down into our layout page! Let’s say that different pages in our app will have their own title tags. We can create a ViewData key/value pair set to title as the property, and unique titles as the values for different pages:

//About.cshtml

@{
    ViewData["Title"] = "About";
}

With our key/value pair defined, all we need to do is simply call the property in our Layout page as so:

<title>@ViewData["Title"] - Razor App</title>

Our Layout will render the value for the title of the page depending on where it’s defined, this allows us to avoid creating unnecessary properties in our PageModel and save us some space!

We don’t always have to use the main layout provided for all of our content. If we want to specify our own layout pages we can do this at the top of our content page. Razor is smart enough to search through a set of predefined locations so we don’t need to provide the whole path of where our layout is located. The filename (.cshtml not needed) should suffice:

 

@{
    Layout = "_NewLayout";
}

 

what is .NET? .NET is a free, cross-platform, open source developer platform for building many different types of applications.
what is the meaning of strongly-typed language? it requires that the programmer specify the data type of every value and expression
what is the meaning of double data type in c#? it means decimal number
what is char data type? it means single character like “a”
define a decimal type value decimal myNumber = 2134.234234324m
double vs float vs decimal? Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float
so we prefer double score = 22.23 not float score = 33.78

double is usually the best choice, because it is more precise than a float, but faster to process than a decimal. However, make sure to use a decimal for financial applications, since it is the most precise.
assume three following variables:
int myInt = 1;
double myDouble = 1.1;
string myString = “1”;

convert:
myInt to double
myDouble to Int
myString to double
double myDoubledInt = myInt;
int myIntedDouble = Convert.ToInt32(myDouble);
int myIntedString = Convert.ToInt32(myString);
string concatenation ? string ali = “ali”
string concatanatedString = ali + “hello world”
what is the meaning of string interpolation? it means using variables in the string
what are ternary operators? string result = (color == “blue”) ? “blue”“NOT blue”;
what is the meaning of overloading?
using System;

namespace MethodOverloading
{
classProgram
{
staticvoidMain(string[] args)
{
NamePets(“Laika”, “Albert”);
NamePets(“Mango”, “Puddy”, “Bucket”);
NamePets();
}
 
staticvoidNamePets(stringpet1, stringpet2)
{
Console.WriteLine($”Your pets {pet1} and {pet2} will be joining your voyage across space!”);
}
 
staticvoidNamePets(stringpet1, stringpet2, stringpet3)
{
Console.WriteLine($”Your pets {pet1}, {pet2}, and {pet3} will be joining your voyage across space!”);
}
 
staticvoidNamePets()
{
Console.WriteLine(“Aw, you have no spacefaring pets :(“);
}
}
}
what is the meaning of following errors:
1- error CS1520: Method must have a return type
2- error CS0161: [MethodName]: not all code paths return a value
3- error CS0029: Cannot implicitly convert type ‘string’ to ‘int’
4- error CS0177: The out parameter ‘success’ must be assigned to before control leaves the current method
5- error CS1620: Argument 2 must be passed with the ‘out’ keyword
1- This error means you must state a return type before the method name
2- This error means that your method doesn’t return a value, when it should
3- In some cases, this error means that your method returns a string when it should be an int (this one can be caused by a lot of things outside of methods)
4- This error means that the out parameter needs to be assigned a value within the method
5- This error means you called a method that expects an ‘out’ parameter but you didn’t use the out keyword when calling it
error CS0515: ‘Forest.Forest()’: static constructor cannot have an access modifier

error CS0120: An object reference is required to access non-static field, method, or property ‘Forest.Grow()’

error CS0176: Member ‘Forest.TreeFacts’ cannot be accessed with an instance reference; qualify it with a type name instead


This error usually means you labeled a static constructor as public or private, which is not allowed

This usually means you tried to reference a non-static member from a class, instead of from an instance

This usually means that you tried to reference a static member from an instance, instead of from the class

what is “out” in c-shart? int number;
bool successInt32.TryParse(“10602”, out number);
// number is 10602 and success is true
int number2;
bool success2Int32.TryParse(” !!! “, out number2);
// number2 is null and success2 is false
how to use “out” in our methods? static string Yell(string phrase, out bool wasYellCalled)
{
wasYellCalled = true;
return phrase.ToUpper();
}

string message = “garrrr”;
Yell(message, out bool flag);
// returns “GARRRR” and flag is true
what is the meaning of fat-arrow? =>
what is the meaning of Expression-bodied? bool isEven(int num) => num % 2 == 0;
sth like arrowFunction in javascript
how Array.Exists or Array.Find() works? it will get an array and a function, then will feed function with every one of the array members until the day that the function returns true
how do you define an array in c-sharp? int[] myArray = {1,2,3,4}
what is Lambda Expressions? bool hasEvenNumber = Array.Exists(numbers, (int num) => num % 2 == 0 );
lambda expression vs expression-bodied? lambda-expressions have no name!
can we remove parameter type? We can remove the parameter type if it can be inferred
can we remove parantheses in lambda expressions? We can remove the parentheses if there is one parameter
how to first define an array and then assign a value to it? int[] myArr;
myArr = new int[] {1,2,3,4}
how to get out of a loop in c#
while (playerIsAlive) 
{ 
// this code will keep running
 
  if (playerIsAlive == false) 
  { 
    // eventually if this stopping condition is true, 
    // it will break out of the while loop
    break; 
   } 
 } 

 

how to get out of a method? return 🙂
class MainClass {
 public static void Main (string[] args) {
   UnlockDoor();
 
  // after it hits the return statement, it will move on to this method
   PickUpSword();
 }
 
 static bool UnlockDoor()
 {
   bool doorIsLocked = true;
 
   // this code will keep running
   while (doorIsLocked)
   {
     bool keyFound = TryKey();
 
      // eventually if this stopping condition is true,
      // it will break out of the while loop
     if (keyFound)
     {
      // this return statement will break out of the entire method
      return true;
     }
   }
   return false;
 }
}

 

how to ignore a loop step in c#
int bats = 10;
 
for (int i = 0; i <= 10; i++)
{
  if (i < 9)
  {  
    continue;
  }
  // this will be skipped until i is no longer less than 9
  Console.WriteLine(i);
}
how to build a data type like string in C#? A class represents a custom data type
how to build a standard class in c#? a class in c# is in file with the same name, for example, to define the following class:
class Forest {…}
it should be in Forest.csfile
what is instantiation? it is the process of creating an instance of a class
how to instantiate a new class in C#? Forest f = new Forest();
what is a class field? public int area;
what is a class property?
public int Area
{
  get { return area; }
  set 
  { 
    if (value < 0) { area = 0; }
    else { area = value; }
  }
}
how to use automatic properties?
// instead of :
public string size;
public string Size
{
  get { return size; }
  set { size = value; }
}
// use:
public string Size
{ get; set; }
how do we set an automatic property very fast in visual studio? usign propfull snippet and double tap
how do we build a constructor fast in c#? ctor
why we need a property?
// assume you have a private variable,
// we make it private cause we just don't want other classes
// to be able to set this property withous certain validation
// , other classes just can read this property
private double balance;
// now to be able to read this from other class and also do a
// certain validation before any kind of seting a new value for
// it, we can make a property for it:
// so final code looks like this:
private double balance;
public double Balance
{
    get
    {
        return balance;
    }
    set
    {
        // do some validation, e.g. convert negative numbers to
        // positive ones, value is a keyword which refers to the
        // value that we give to this property
        balance = value;
    }
}

 

how to define a constructor in C#?
class Forest
{
  public int Area;
 
  public Forest(int area)
  {
    Area = area;
  }
}
what is an object in C#? actually an instant of a class
what is the meaning of encapsulating? bundling related data & methods into one logical group
what is the meaning of static? static means “associated with the class, not an instance”. Thus any static member is accessed from the class
// e.g: in following example Definition of Forest class is static:
class Forest
{
  private static string definition;
  public static string Definition
  { 
    get { return definition; }
    set { definition = value; }
  }
}
// so you can not use e.g: f.Definition but can use Forest.Definition
why first method in Program class should be static as we see in:
Class Program {
    static void Main () {}
}
because we had nothing before of starting the program, so we didn’t event actually instantiate a Program class before
what is notable about static methods? a static method can only access other static members
what is notable about static properties? if we have a static method and we want to use a class property in it, that property should be static too
why?
because if that property wasn’t static, when a static method is launching we actually have not that property because we haven’t instantiated that property before
what is notable about static constructor? A static constructor does not accept an access modifier like private or …
what is the usage of static constructor?
when a static constructor run?

answer 1:
Typically we use static constructors to set values to static fields and properties. like:

class Forest 
{
  static Forest()
  { /* ... */ }
}

in other word, if you want e.g. use a method from a class instatiated object you shouldn’t use static keyword for it, otherwise you must
e.g. you never gona use 
Porgram p = new Program() and then sth like p.Main() !!! so you will use static for your Main method 🙂

answer 2:

  • Before an object is made from the type.
    Forest f  = new Forest();
  • Before a static member is accessed.
    Forest.Define();
what is the usage of a static class? A static class cannot be instantiated, so you only want to do this if you are making a utility or library, like Math or Console.

These two common classes are static because they are just tools — they don’t need specific instances and they don’t store new information.

Math.Min(34, 54);
Console.WriteLine("yeehaw!");
// these are two static classes calling two static methods.
what are interfaces?

sets of actions and values that describe how a class can be used. e.g.:

interface IAutomobile
{
  string Idget; }
  void Vroom(); // we don’t need body  of methods in interfaces
}

// Interface vs Class infographic:
Class       | | | |
Interface     | |
// indeed, when we implement an interface for a class
// we are telling that class, you must have all of these
// properties/methods but you can have more
// e.g. you shoudld have wheels and body but you can also
// have headsup displayer

 

how to naming and organizing interfaces? Every interface should have a name starting with “I”, and we will put them in separate files with same names, exactly like classes
what does interfaces doesn’t cover? In fact, interfaces cannot specify two types of members that are commonly found in classes
how to use inheritance in C#? class Sedan : Vehicle, IAutomobile
{
}


The above code means that Sedan will inherit all the functionality of the Vehicle class, and it “promises” to implement all the functionality in the IAutomobile interface
how to Access Inherited Members with Base?
//For example, in Sedan:

base.SpeedUp();
//refers to the SpeedUp() method in Vehicle.

//There’s special syntax for calling the superclass constructor:

class Sedan : Vehicle
{
  public Sedan (double speed) : base(speed)
  {
  }
}
how to
// In the superclass, we mark the method in question as virtual, which tells the computer “this member might be overridden in subclasses”:

public virtual void SpeedUp()
// In the subclass, we mark the method as override, which tells the computer “I know this member is defined in the superclass, but I’d like to override it with this method”:

public override void SpeedUp()
// As an aside: there’s another way to solve this problem. Instead of using virtual and override to override a member, we can define a new member with the same name. Essentially, the inherited member still exists, but it is “hidden” by the member in the subclass.

 

what is the meaning of abstracting a member in C#? and how do you do that? public abstract string Describe()
assume if top line is in Vehicle Class, so if you ever wanted to inherit a class from Vehicle, you must define a Describe() method since Vehicle won’t give you any functionality to inherit

If one member of a class is abstract, then the class itself can’t really exist as an instance. Imagine calling Vehicle.Describe(). It doesn’t make sense because it doesn’t exist! This means that the entire Vehicle class must be abstract. Label it with abstract as well:
abstract class Vehicle
can a private method be virtual? no! since a private method can not be used in sub-classes, so being able to override it or not in a sub-class is non-sense
can a partial method be virtual? no! a partial method 
class Tractor : IMachine
{}

in above code tractor implements IMachine, or vise-versa
The Tractor class implements the IMachine interface
do we have refrences in C#? of course yes, for example assume following code:
Dissertation diss1 = new Dissertation();
Dissertation diss2 = diss1;
diss1.CurrentPage = 0;
diss2.CurrentPage = 16;
Console.WriteLine(diss1.CurrentPage);
Console.WriteLine(diss2.CurrentPage);
// above code will print 16, 16 not 0, 16

Classes are reference types. That means that when we create a new instance of a class and store it in a variable, the variable is a reference to the object.

what kind of variables do we have in C#? To better grasp the idea of reference types, let’s look at the other kind of type: value types. While reference-type variables refer to a place in memory, value-type variables hold the actual data
value-type variables hold a value, on the other hand reference-type variables just hold a reference
all of the “primitive” data types are value value type like:
int, double, boo, char
is string value-type or reference-type? what is the difference of String and string? reference-type! they are equivalent
String, or string, is a class that represents text. Technically its value is stored as a collection of char objects.
but:

Since it is a class, it is a reference type. In some cases its behavior looks like a value type:

  • string reference will always point to the original object, so “modifying” one reference to a string will not affect other references
    // Example 1
    string dog = "chihuahua";
    string tinyDog = dog;
    dog = "dalmation";
    Console.WriteLine(dog);
    // Output: "dalmation"
    Console.WriteLine(tinyDog);
    // Output: "chihuahua"
  • Comparing strings with the equality operator (==) performs a value, not referential, comparison
    string s = "hello";
    string t = "hello";
    // b is true
    bool b = (s == t);
  • Like other reference types, string references can be null or unassigned. They can also have a third value: empty.
    string s; // Unassigned
    string s2 = null; // Null
    string s3 = ""; // Empty string
    string s4 = String.Empty; // Also empty string
    Console.WriteLine(s3 == s4); // This prints true

     

string empty vs null vs unassigned?
  • unassigned means that the programmer did not give the variable any value
  • null means that the programmer intentionally made the variable refer to no object
  • an empty string signifies a piece of text with zero characters. This is often used to represent a blank text field. It can be represented by "" or String.Empty

The Microsoft Programming Guide suggests using String.Empty or "" instead of null to avoid NullReferenceException errors.

We can check for null OR empty strings using the static String method IsNullOrEmpty(). It’s explained in more detail in the documentation.

value comparison vs referential comparison
// value comparison
int int1 = 6;
int int2 = 6;
Console.WriteLine(int1 == int2); // Output: true

// referential comparison
Dissertation d1 = new Dissertation(50);
Dissertation d2 = new Dissertation(50);
Console.WriteLine(d1 == d2); // Output: false

When we compare reference types with ==, the C# compiler performs a referential comparison, which means it checks if two variables refer to the same memory location. For example, this prints false because d1 and d2 refer to two different locations in memory (even though they contain objects with the same values)

References of Different Types

References of Different Types

Before going any further, let’s remind ourselves that Dissertation implements IFlippable, which has the CurrentPage property and Flip() method. You’ll need this info in a minute.

In our previous example both references to the Dissertation object were of type Dissertation:

Dissertation diss1 = new Dissertation();
Dissertation diss2 = diss1;

Whenever we use diss1 and diss2 we can handle the Dissertation object as if it were a Dissertation type. Since Dissertation also implements the IFlippable interface, we can reference it that way too:

Dissertation diss = new Dissertation(50);
IFlippable fdiss = diss;

Now diss and fdiss refer to the same object, but fdiss is an IFlippable reference, so it can ONLY use IFlippable functionality:

diss.Flip();
fdiss.Flip();
Console.WriteLine(diss.Define());
// This causes an error!
Console.WriteLine(fdiss.Define());

This last line causes an error because Define() is not a method in the IFlippable interface. The other lines do NOT cause errors because they use members that both IFlippable and Dissertation have.

This rule also applies to base classes too, so we can refer to a Dissertation object as Book.

Dissertation diss = new Dissertation(50);
Book bdiss = diss;
Console.WriteLine(diss.Title);
Console.WriteLine(bdiss.Title);
diss.Define();
// This causes an error!
bdiss.Define();

Title is defined for Book, so no error is thrown there. Define(), however, is not defined for the Book class, so we can’t use it with Book references.

what is the meaning of polymorphism?

to have the same interface for multiple data types. This is a common concept across many programming languages, and it’s called polymorphism.

The concept really includes two related ideas. A programming language supports polymorphism if:

  1. Objects of different types have a common interface (interface in the general meaning, not just a C# interface), and
  2. The objects can maintain functionality unique to their data type
In C# what is the type of the reference that can be used for all objects? Object
all classes are drived from what in C#?

Object

so Objects are the most top superClass for all classes

so we can have:

Object o1 = new Dissertation();
Object o2 = new Diary();
Object o3 = new Random();
Object o4 = new Forest("Amazon");

but if we do so, we will loose 2 things:
1- We lose all of a specific type’s specific functionality when we reference it as an Object type.
2- We would also lose the automatic type-checking that saves us from type errors

what is the hidden part of following code?
class Book
{}
class Book : Object
{}
does value-type variables inherit from Objects? yes, we can confirm this since following code doesn’t throw any kind of errors:
Object o5 = 21;
Object o6 = false;
Object o7 = "Hello you!";
what are most usefull common objects members?
and which ones are virtual and can be overridden?
Object o1new Object();

Type to1.GetType(); // t is System.Object

string so1.ToString();

Console.WriteLine(s); // Prints “System.Object”

Object o2o1;

bool bo1.Equals(o2); // Equals true
——
ToString & Equals
why we need lists ? why not arrays?
  • They have a limited length
  • You have to keep track of the number of elements in the array using a separate index
  • You can only edit one element at a time
what are Generic collections? Generic collections are data structures that are defined with a generic type. Each class is defined generally without a specific type in mind

so e.g. List<T> is a generic collection
What is .NET?

Formally, .NET is “an open source developer platform, created by Microsoft, for building many different types of applications. You can write .NET apps in C#, F#, Visual C++, or Visual Basic.”

Informally, .NET is the tool that lets you build and run C# programs (we’ll avoid F#, Visual C++, Visual Basic for now)
in other words: To build programs with C#, you need the .NET platform

When you download .NET, you’re really downloading a bunch of programs that:

  • Translate your C# code into instructions that a computer can understand
  • Provide utilities for building software, like tools for printing text to the screen and finding the current time
  • Define a set of data types that make it easier for you to store information in your programs, like text, numbers, and dates
what are .Net Core and .Net Framework?
  • .NET Framework is the original version of .NET that only runs on Windows computers.
  • .NET Core is the new, cross-platform version of .NET that runs on Windows, MacOS, and Linux computers. Since it’s more flexible and Microsoft is actively enhancing this version, we’ll be using this one throughout the path.

Conveniently, Microsoft itself plans to rename .NET Core to .NET towards the end of 2020.

how to get .Net Core?
————————-
what about ASP.NET?
1- using Visual Studio
2- .NET SDK (software development kit):
It also comes with the .NET platform, but it has no code editing tools. Instead of an app on your computer, the SDK is accessed via a command-line interface (CLI): dotnet new for example
—————————
If we want to build programs specifically for the web, like websites, you’ll need to add more tools on top of .NET. One of the most popular is ASP.NET. To keep them separate, developers call .NET a platform and ASP.NET a framework.
what is “Razor Pages architecture” ?

The Razor Pages architecture goes like this: Every page of our website is represented by two files:

  • view page, that displays information, and
  • page model, which handles the accessing and processing of information.

Razor Pages can also be used to make things other than web pages, like APIs and microservices. In those cases we wouldn’t need a view page, we’d just use page models.

what does xaml stands for? extensible application markup language
how to define properties for a tag in xaml? 1- method 1:
<Grid Margin=”10″></Gird>
2- method 2:
<Grid.Margin>10</Grid.Margin>
how to use grid system in xaml?
<Grid Margin="10">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Label Content="0" 
           Grid.ColumnSpan="4"
           VerticalContentAlignment="Bottom"
           HorizontalContentAlignment="Right"
           Background="white"/>
    <Button Margin="10"
            Background="Red"
            Content="1"
            Grid.Row="1"/>
</Grid>

 

how to use stackpanel in xaml?
<StackPanel VerticalAlignment="Center" Margin="40,10">
            <Label Content="Paradise-hub" Margin="0,0,0,10" Foreground="white" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="72" FontFamily="Cambria"/>
            <TextBox Text="0" Margin="0,0,0,10"/>
            <TextBox Text="0" Margin="0,0,0,10"/>
            <Button Content="Calculate" Background="DodgerBlue" Foreground="White" Padding="10"/>
        </StackPanel>

 

how to right line breaks in xaml files?
 <TextBlock Text="Line1&#x0a;Line 2"/>

or:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>
how to use event handlers in wpf? assume that you want to call private void acBtn_click () {} :
* method 1: from xaml:
<Button Click=”acBtn_click”/>
* method 2: from c#:
`acBtn.Click += acBtn_click;
how to create an Enum type in cSharp? public class enum SelectedOperator
{
    Addition,
    Substraction,
    Multiplication,
    Division
}
now you can use it like this:
SelectedOperator selectedOperator;

selectedOperator = SelectedOperator.Multiplication;
what is NuGet? NuGet is a package manager
what is the name of most know NuGet packages? 1- sqlite-net-pcl
2- 
how can we use using statement (not using namespace) we can use it if the class is implemented on IDisposable interface, e.g. SQLiteConnection
what are linqs in simple words? assume following list:
List<Contact> contactsList;
this list has no .Where(... property for example, but if you use System.linq you can have other properties for certain types such as Lists

you can use linqs in two approach:
// approach 1:
var filteredList = contacts.Where(c => c.Name.ToLower().Contains(searchTextBox.Text.ToLower())).ToList();
// approach 2:
var filteredList2 = (from c2 in contacts
                                   where c2.Name.ToLower().Contains(searchTextBox.Text.ToLower())
                                   select c2.Id).ToList();
how can we use new syntax for using statement in c# 8?
// instead of :
using(SQLiteConnection conn = new(App.DbPath))
{
    conn.CreateTable<Contact>();
    contacts = conn.Table<Contact>().ToList();
}
// we can use :
using SQLiteConnection conn = new(App.DbPath);
conn.CreateTable<Contact>();
contacts = conn.Table<Contact>().ToList();

// because It tells the compiler that the variable being
// declared should be disposed at the end of the enclosing scope
sdsd  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   

Leave a Reply

Your email address will not be published. Required fields are marked *