C# Fields Tutorial

Programming with Mosh · Beginner ·🛠️ AI Tools & Apps ·8y ago

Key Takeaways

This video tutorial by Programming with Mosh covers the basics of fields in C#, including initialization and read-only fields, and demonstrates how to use them in a customer class example.

Full Transcript

okay we got two fields at the beginning of this section I gave you a brief explanation of fields a film is like variable that we declare at the class level and we use that to store data about the class so in this lecture I'm gonna talk about a couple of different ways to initialize fields and then I'll talk about the concept of read-only fields so in the last lecture you saw me declaring a class called customer which had a list of orders and you also saw how I initialize that field using the default or the parameterless constructor while this approach is perfectly fine there is also another school of thought when it comes to initializing fields some developers believe we should use constructors only when we need to initialize our fields based on the values passed from the outside so in this case we are initializing the orders field without any external values the constructor as you see here has no parameters so in situations like that there is another way to initialize the orders field and that looks like the code you see here so we can directly initialize the orders field without the need to create a constructor this approach has an extra benefit and that is we can have multiple constructors and no matter which one is called the orders field will always be initialized to an empty list we'll explore that later when you start coding okay now let's take a look at read-only fields we can declare a field with the read-only modifier to make sure that that field is only assigned once so in that case that fill has to be initialized either directly like the slide you see here or in one of the constructors of the class you might wonder why do we need something like that the reason is to create some kind of safety in our application to improve robustness for example take a look at this customer class here by declaring the orders field as read-only I'll make sure that we'll only have one list where we will keep the list of orders if I accidentally as a developer try to reinitialize this field in another method the data that we had in the field will not be lost it's easier to explain that using an example so let's start coding and see this concepts in action okay let's start by creating a customer class so public class customer a couple of fields so public and ID public string name we can also create an order class public class order I'm gonna leave the implementation of this class for now we don't really need it for this example all we need to do is to create a list of orders and the customer so public list of order now let's declare a couple of instructors for this class so see tour make it just an ID so these that ID equals ID the second one is gonna get an ID and a name and just to recap what we learned in the Constructors lecture we can use it this keyword here and instead of repeating the initialization of the ID like the code you see here we can delegate the control to this constructor here so I'm just gonna use that this keyword has to ID at this point this constructor will be called so the ID will be initialized based on what we get here and then here I can say this name a cause name now if you remember from the lecture about constructors explained why we need to initialize these orders to an empty list just to recap whenever you have a class like customer and inside that class you have a list you should always initialize that list to an empty list now the technique I showed you in that lecture was to create a default constructor like the one here and set the orderers to an empty list like here this approach is perfectly fine but there is a slight problem with that and that is if you use any of these constructors here so this one or this one we have to make sure that the default constructor is always called first so the orders field will be initialized some developers argue and say no we shouldn't initialize feels like the orders here because orders is not dependent on any parameters from the outside so what we can do is we can get rid of this constructor and initialize the orders field here this way no matter which constructor is going to be called the orders field will always be initialized an empty list some developers do not like this approach because they don't like the idea of initializing some of the fields here while declaring them versus initializing the others in the Constructors it's entirely up to you it's more a personal taste I wanted to show you both approaches so you know what is possible they approach you choose is up to you but what I want to emphasize to you is to be consistent with your approach make sure you use the same approach everywhere this way your code would be cleaner okay now let's move on and look at read-only modifier so here I want to declare a method let's call it promote and the intention is this method will promote this customer to a gold customer I'm gonna leave the implementation here let's just put some comment but I want to show you a mistake that I as a developer and accidentally make let's say if I accidentally reinitialize these orders here what would happen so what I'm gonna do is to clean up our code I'm gonna put this customer class and a separate file so cursor here I explained this earlier so with resharper Alt + Enter and enter again now this class ended up in a separate file so that file is customer that's yes now we go back to program we can do the same with the order class back to the program now the code is cleaner let's create a customer object so if our customer equals new customer we're expected to supply an ID and/or a name because we don't have a default or parameterless constructor so look here we've got two constructors I'm gonna use the first one doesn't really matter I'm gonna add two orders to this customer so customer dot orders add new order and let's just copy paste this line so at this point if I display the number of orders the customer has we should see two on the console so let's quickly do that customer that orders that count let's run the application so we got two on the console now let me show you something imagine here we make a call to the promote method this method because of a bug accidentally reinitialized the orders field so now if you run the application all the data that we had in the orders field is lost we have zero this is where you use the read-only modifier go back to the customer there are situations where you know that this field should be initialized only once that's where you decorate that with the read-only modifier this way if you accidentally reset that field in the code you're gonna get a compile time error first of all we can immediately see this error here by the red underline it says read-only field cannot be used as an assignment target so if you don't see the red error when you compile the application you're definitely gonna see that so a read-only field cannot be assigned - except in a constructor or a variable initializer so what this means is this line is not acceptable we can only initialize a read-only field either here directly when we are declaring that or in the constructor so really is one of the ways that you can improve the robustness of your application that's it for this lecture I hope you enjoyed it and thank you for watching hi guys ma chere I hope you're having a fantastic day or night wherever you are in the world this tutorial you have been watching is actually part of one of my C sharp courses where you will learn everything about classes interfaces and object-oriented programming in case you're interested to enroll in the full course I've put the link for you in the video description and if not that's perfectly fine have a great day

Original Description

C# Fields Tutorial 🔥Get the COMPLETE Course: http://bit.ly/2LhL39u SUBSCRIBE FOR MORE VIDEOS! https://www.youtube.com/channel/UCWv7vMbMWH4-V0ZXdmDpPBA?sub_confirmation=1 STAY IN TOUCH https://www.facebook.com/programmingwithmosh/ https://twitter.com/moshhamedani
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Programming with Mosh · Programming with Mosh · 0 of 60

← Previous Next →
1 6 Visual Studio Tips to Increase Your Productivity | Mosh
6 Visual Studio Tips to Increase Your Productivity | Mosh
Programming with Mosh
2 Visual Studio Keyboard Shortcuts that Speed Up Debugging Applications | Mosh
Visual Studio Keyboard Shortcuts that Speed Up Debugging Applications | Mosh
Programming with Mosh
3 Backbone.js Tutorial Part 2 - Backbone.js Models: Working with Model Attributes
Backbone.js Tutorial Part 2 - Backbone.js Models: Working with Model Attributes
Programming with Mosh
4 Backbone.js Tutorial Part 3 - Backbone.js Models: Model Validation
Backbone.js Tutorial Part 3 - Backbone.js Models: Model Validation
Programming with Mosh
5 Backbone.js Tutorial Part 4 - Backbone.js Models: Model Inheritance
Backbone.js Tutorial Part 4 - Backbone.js Models: Model Inheritance
Programming with Mosh
6 Backbone.js Tutorial Part 1 - Backbone.js Models: Creating Models
Backbone.js Tutorial Part 1 - Backbone.js Models: Creating Models
Programming with Mosh
7 Backbone.js Tutorial Part 5 - Backbone.js Models: Syncing Models with the Server
Backbone.js Tutorial Part 5 - Backbone.js Models: Syncing Models with the Server
Programming with Mosh
8 Backbone.js Tutorial Part 6 - Backbone.js Collections: Creating Collections
Backbone.js Tutorial Part 6 - Backbone.js Collections: Creating Collections
Programming with Mosh
9 Backbone.js Tutorial Part 7 - Backbone.js Collections: Working with Collections
Backbone.js Tutorial Part 7 - Backbone.js Collections: Working with Collections
Programming with Mosh
10 Backbone.js Tutorial Part 8 - Backbone.js Collections: Fetching Collections from the Server
Backbone.js Tutorial Part 8 - Backbone.js Collections: Fetching Collections from the Server
Programming with Mosh
11 Backbone.js Tutorial Part 9 - Backbone.js Views: Creating Views
Backbone.js Tutorial Part 9 - Backbone.js Views: Creating Views
Programming with Mosh
12 Backbone.js Tutorial Part 10 - Backbone.js Views: Passing Data to Views
Backbone.js Tutorial Part 10 - Backbone.js Views: Passing Data to Views
Programming with Mosh
13 Backbone.js Tutorial Part 11 - Backbone.js Views: Handling the DOM Events
Backbone.js Tutorial Part 11 - Backbone.js Views: Handling the DOM Events
Programming with Mosh
14 Backbone.js Tutorial Part 12 - Backbone.js Views: Handling the Model Events
Backbone.js Tutorial Part 12 - Backbone.js Views: Handling the Model Events
Programming with Mosh
15 Backbone.js Tutorial Part 13 - Backbone.js Views: Handling Collection Events
Backbone.js Tutorial Part 13 - Backbone.js Views: Handling Collection Events
Programming with Mosh
16 Backbone.js Tutorial Part 14 - Backbone.js Views: Templating
Backbone.js Tutorial Part 14 - Backbone.js Views: Templating
Programming with Mosh
17 Clean Code: Learn to write clean, maintainable and robust code
Clean Code: Learn to write clean, maintainable and robust code
Programming with Mosh
18 C# Events and Delegates Made Simple | Mosh
C# Events and Delegates Made Simple | Mosh
Programming with Mosh
19 C# Generics Tutorial: Whats and Whys | Mosh
C# Generics Tutorial: Whats and Whys | Mosh
Programming with Mosh
20 Debugging C# Code in Visual Studio | Mosh
Debugging C# Code in Visual Studio | Mosh
Programming with Mosh
21 Repository Pattern with C# and Entity Framework, Done Right | Mosh
Repository Pattern with C# and Entity Framework, Done Right | Mosh
Programming with Mosh
22 Angular 2 Tutorial for Beginners: Learn Angular 2 from Scratch | Mosh
Angular 2 Tutorial for Beginners: Learn Angular 2 from Scratch | Mosh
Programming with Mosh
23 Architecture of Angular 2+ Apps
Architecture of Angular 2+ Apps
Programming with Mosh
24 Working with Components in Angular
Working with Components in Angular
Programming with Mosh
25 C# Tutorial For Beginners - Learn C# Basics in 1 Hour
C# Tutorial For Beginners - Learn C# Basics in 1 Hour
Programming with Mosh
26 Difference between Junior and Senior Developers
Difference between Junior and Senior Developers
Programming with Mosh
27 Step-by-step ASP.NET MVC Tutorial for Beginners | Mosh
Step-by-step ASP.NET MVC Tutorial for Beginners | Mosh
Programming with Mosh
28 [Pluralsight]: Become a Full-stack .NET Developer
[Pluralsight]: Become a Full-stack .NET Developer
Programming with Mosh
29 Xamarin Forms Tutorial: Build Native Mobile Apps with C#
Xamarin Forms Tutorial: Build Native Mobile Apps with C#
Programming with Mosh
30 Value Types and Reference Types in JavaScript
Value Types and Reference Types in JavaScript
Programming with Mosh
31 Using Redux in Angular 2+ Apps | Mosh
Using Redux in Angular 2+ Apps | Mosh
Programming with Mosh
32 Testing Angular 2+ Apps with Jasmine and Karma | Mosh
Testing Angular 2+ Apps with Jasmine and Karma | Mosh
Programming with Mosh
33 Profile and optimize your Angular 2 apps
Profile and optimize your Angular 2 apps
Programming with Mosh
34 Build a Real-world App with ASP.NET Core and Angular 2
Build a Real-world App with ASP.NET Core and Angular 2
Programming with Mosh
35 Entity Framework 6 Tutorial: Learn Entity Framework 6 from Scratch
Entity Framework 6 Tutorial: Learn Entity Framework 6 from Scratch
Programming with Mosh
36 Two-way Binding and ngModel in Angular 4
Two-way Binding and ngModel in Angular 4
Programming with Mosh
37 Udemy Live 2017: Teaching Tech Panel
Udemy Live 2017: Teaching Tech Panel
Programming with Mosh
38 Demo of An E-commerce App Built with Angular, Firebase and Bootstrap 4
Demo of An E-commerce App Built with Angular, Firebase and Bootstrap 4
Programming with Mosh
39 My Brand New Angular Course
My Brand New Angular Course
Programming with Mosh
40 TypeScript Tutorial - TypeScript for React - Learn TypeScript
TypeScript Tutorial - TypeScript for React - Learn TypeScript
Programming with Mosh
41 Access Modifiers in TypeScript
Access Modifiers in TypeScript
Programming with Mosh
42 TypeScript Interfaces
TypeScript Interfaces
Programming with Mosh
43 TypeScript Classes
TypeScript Classes
Programming with Mosh
44 TypeScript Constructors
TypeScript Constructors
Programming with Mosh
45 TypeScript Properties
TypeScript Properties
Programming with Mosh
46 Angular Tutorial for Beginners: Learn Angular & TypeScript
Angular Tutorial for Beginners: Learn Angular & TypeScript
Programming with Mosh
47 AngularJS vs Angular 2 vs Angular 4 | Mosh
AngularJS vs Angular 2 vs Angular 4 | Mosh
Programming with Mosh
48 Angular Material Tutorial | Mosh
Angular Material Tutorial | Mosh
Programming with Mosh
49 Angular Animations Tutorial | Mosh
Angular Animations Tutorial | Mosh
Programming with Mosh
50 Firebase in Angular Applications | Mosh
Firebase in Angular Applications | Mosh
Programming with Mosh
51 Deploying Angular Applications | Mosh
Deploying Angular Applications | Mosh
Programming with Mosh
52 Building Forms in Angular Apps | Mosh
Building Forms in Angular Apps | Mosh
Programming with Mosh
53 Directives in Angular Applications
Directives in Angular Applications
Programming with Mosh
54 Routing and Navigation in Angular | Mosh
Routing and Navigation in Angular | Mosh
Programming with Mosh
55 Angular 4 in 40 Minutes
Angular 4 in 40 Minutes
Programming with Mosh
56 [NEW COURSE] Unit Testing for C# Developers
[NEW COURSE] Unit Testing for C# Developers
Programming with Mosh
57 Unit Testing C# Code - Tutorial for Beginners
Unit Testing C# Code - Tutorial for Beginners
Programming with Mosh
58 C# Classes Tutorial | Mosh
C# Classes Tutorial | Mosh
Programming with Mosh
59 C# Object Initializers Tutorial
C# Object Initializers Tutorial
Programming with Mosh
60 C# Constructors Tutorial | Mosh
C# Constructors Tutorial | Mosh
Programming with Mosh

This tutorial teaches the basics of fields in C#, including how to initialize them and use read-only fields, with a focus on object-oriented programming principles.

Key Takeaways
  1. Declare a field at the class level
  2. Initialize a field using a constructor or directly
  3. Use the read-only modifier to ensure a field is only assigned once
  4. Create a customer class with fields and constructors
  5. Demonstrate the use of read-only fields to prevent accidental reinitialization
💡 Using read-only fields can improve the robustness of an application by preventing accidental reinitialization of fields.

Related AI Lessons

Up next
How to Open HPL Files (HP-GL Plotter)
File Extension Geeks
Watch →