{"id":280,"date":"2022-01-03T10:36:13","date_gmt":"2022-01-03T03:36:13","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=280"},"modified":"2022-06-03T13:43:00","modified_gmt":"2022-06-03T06:43:00","slug":"csharp-public-private","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-public-private\/","title":{"rendered":"C# Public &#038; Private"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the C# public and private keywords and the differences between them.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the access modifiers in C#<\/h2>\n\n\n\n<p>When declaring a field or a method inside a class, you can specify an accessibility level. In the <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-class\/\"><code>class<\/code> tutorial<\/a>, you learned how to use the <code>public<\/code> keyword to make a field or a method to be accessible from both inside and outside of a class.<\/p>\n\n\n\n<p>The <code>public<\/code> keyword is an access modifier. Besides the public access modifier, C# has other access modifiers as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>private<\/li><li>protected<\/li><li>internal<\/li><li>protected internal<\/li><li>private protected<\/li><\/ul>\n\n\n\n<p>In this tutorial, you&#8217;ll focus on the public and private access modifiers.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The public access modifier<\/h2>\n\n\n\n<p>When using the <code>public<\/code> keyword for a field or a method, you can access the field and method from both inside and outside of a class.<\/p>\n\n\n\n<p>For example, the following defines the <code>Person<\/code> class with two public fields <code>FirstName<\/code> and <code>LastName<\/code> and one public methods <code>GetFullName()<\/code>:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-comment\">\/\/ Person.cs<\/span>\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> FirstName;\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> LastName;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> <span class=\"hljs-title\">GetFullName<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{<span class=\"hljs-keyword\">this<\/span>.FirstName}<\/span> <span class=\"hljs-subst\">{<span class=\"hljs-keyword\">this<\/span>.LastName}<\/span>\"<\/span>;\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Since the fields and methods of the <code>Person<\/code> class are public, you can access them from the outside of the class like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-comment\">\/\/ Program.cs<\/span>\n\nPerson p1 = <span class=\"hljs-keyword\">new<\/span>();\n\np1.FirstName = <span class=\"hljs-string\">\"John\"<\/span>;\np1.LastName = <span class=\"hljs-string\">\"Doe\"<\/span>;\n\nConsole.WriteLine(p1.GetFullName());<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">John Doe<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">The private access modifier <\/h2>\n\n\n\n<p>The <code>private<\/code> access modifier uses the <code>private<\/code> keyword. When using the <code>private<\/code> keyword for a field or method, you can only access the private field or method inside the same class. It means that you cannot access the private field or method outside of the class.<\/p>\n\n\n\n<p>Typically, you use the private access modifier to prevent direct access to fields of a class. Also, you use the private method when you want to use that method only within the class. <\/p>\n\n\n\n<p>If you don&#8217;t specify an access modifier for a member, that member will be private.<\/p>\n\n\n\n<p>The following program prompts you to enter your first name and last name and assigns values to the <code>FirstName<\/code> and <code>LastName<\/code> fields of the <code>Person<\/code>&#8216;s object:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-comment\">\/\/ Program.cs<\/span>\n\nPerson p1 = <span class=\"hljs-keyword\">new<\/span>();\n\nConsole.WriteLine(<span class=\"hljs-string\">\"Enter the first name and last name:\"<\/span>);\n\n<span class=\"hljs-keyword\">string<\/span>? firstName = Console.ReadLine();\n<span class=\"hljs-keyword\">string<\/span>? lastName = Console.ReadLine();\n\n<span class=\"hljs-keyword\">if<\/span> (!<span class=\"hljs-keyword\">string<\/span>.IsNullOrEmpty(firstName))\n{\n    p1.FirstName = firstName;\n}\n\n<span class=\"hljs-keyword\">if<\/span> (!<span class=\"hljs-keyword\">string<\/span>.IsNullOrEmpty(lastName))\n{\n    p1.LastName = lastName;\n}\n\nConsole.WriteLine(p1.GetFullName());<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>In this example, before assigning the <code>firstName<\/code> and <code>lastName<\/code> variables to the <code>FirstName<\/code> and <code>LastName<\/code> fields, we check if the input strings are not null or empty.<\/p>\n\n\n\n<p>However, if we need to do this in multiple places in the program, we have to duplicate the code. Also, if we want to change the validation logic, we need to change it in various places. So the code becomes very difficult to maintain. And it violates the DRY (Don&#8217;t Repeat Yourself) principle in programming.<\/p>\n\n\n\n<p>To fix this, you can follow these steps:<\/p>\n\n\n\n<p>First, wrap the checking logic as a private method in the <code>Person<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">bool<\/span> <span class=\"hljs-title\">isValidName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>? name<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">return<\/span> !<span class=\"hljs-keyword\">string<\/span>.IsNullOrEmpty(name);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, make the <code>firstName<\/code> and <code>lastName<\/code> fields private:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">string<\/span> firstName;\n<span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">string<\/span> lastName;<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>By convention, private fields are camelCase like <code>firstName<\/code> and <code>lastName<\/code>. Therefore, we rename the field names to follow the community convention.<\/p>\n\n\n\n<p>Because the <code>firstName<\/code> and <code>lastName<\/code> fields are private, we cannot access them outside the <code>Person<\/code> class. Therefore, to assign values to these fields, we can define two public methods <code>SetFirstName()<\/code> and <code>SetLastName()<\/code>.<\/p>\n\n\n\n<p>Third, add the <code>SetFirstName()<\/code> and <code>SetLastName()<\/code> methods to the <code>Person<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Person <span class=\"hljs-title\">SetFirstName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>? firstName<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">if<\/span> (isValidName(firstName))\n    {\n        <span class=\"hljs-keyword\">this<\/span>.firstName = firstName;\n    }\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>;\n}\n\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Person <span class=\"hljs-title\">SetLastName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>? lastName<\/span>)<\/span>\n{\n    <span class=\"hljs-keyword\">if<\/span> (isValidName(lastName))\n    {\n        <span class=\"hljs-keyword\">this<\/span>.lastName = lastName;\n    }\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>;\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Inside these methods, we call the <code>isValidName()<\/code> method to validate the name before assigning it to the corresponding private field.<\/p>\n\n\n\n<p>Note that you&#8217;ll learn how to do it more elegantly by using a <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-property\/\">property with the getters and setters later<\/a>.<\/p>\n\n\n\n<p>The following shows the complete <code>Person<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-8\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-comment\">\/\/ Person.cs<\/span>\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Person<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">string<\/span> firstName;\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">string<\/span> lastName;\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">string<\/span> <span class=\"hljs-title\">GetFullName<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">$\"<span class=\"hljs-subst\">{<span class=\"hljs-keyword\">this<\/span>.firstName}<\/span> <span class=\"hljs-subst\">{<span class=\"hljs-keyword\">this<\/span>.lastName}<\/span>\"<\/span>;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">bool<\/span> <span class=\"hljs-title\">isValidName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> name<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">return<\/span> !<span class=\"hljs-keyword\">string<\/span>.IsNullOrEmpty(name);\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Person <span class=\"hljs-title\">SetFirstName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> firstName<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">if<\/span> (isValidName(firstName))\n        {\n            <span class=\"hljs-keyword\">this<\/span>.firstName = firstName;\n        }\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>;\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> Person <span class=\"hljs-title\">SetLastName<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> lastName<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">if<\/span> (isValidName(lastName))\n        {\n            <span class=\"hljs-keyword\">this<\/span>.lastName = lastName;\n        }\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">this<\/span>;\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-8\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Now, you can create the <code>Person<\/code>&#8216;s object and call the public methods <code>SetFirstName()<\/code> and <code>SetLastName()<\/code> to set the first name and last name private fields:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-9\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-comment\">\/\/ Program.cs<\/span>\n\nPerson p1 = <span class=\"hljs-keyword\">new<\/span>();\n\nConsole.WriteLine(<span class=\"hljs-string\">\"Enter the first name and last name:\"<\/span>);\n\n<span class=\"hljs-keyword\">string<\/span>? firstName = Console.ReadLine();\n<span class=\"hljs-keyword\">string<\/span>? lastName = Console.ReadLine();\n\n\n<span class=\"hljs-keyword\">string<\/span> name = p1.SetFirstName(firstName)\n                .SetLastName(lastName)\n                .GetFullName();\n\nConsole.WriteLine(name);<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-9\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li>Use the public access modifier for the fields and methods that are accessible from both inside and outside the class.<\/li><li>Use the private access modifier for the fields and methods that are accessible only within the same class.<\/li><\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"280\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-public-private\/\"\n\t\t\t\tdata-post-title=\"C# Public &#038; Private\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"280\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-tutorial\/csharp-public-private\/\"\n\t\t\t\tdata-post-title=\"C# Public &#038; Private\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about the C# public and private keywords and the differences between them.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":7,"menu_order":29,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-280","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=280"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/280\/revisions"}],"predecessor-version":[{"id":714,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/280\/revisions\/714"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/7"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}