locked
What is abstract class and Interface class with simple example RRS feed

  • Question

  • User-471420332 posted

    What is abstract class and Interface class with simple example, how to implement abstract class and Interface both at what scenario in my C# asp.net web form project

    I am boring with this type of coding Page_Load method have another method getdata(); to call or fill  data or send data.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public partial class Default3 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    getdata();
    }

    public void getdata()
    {
    //fill gridview using datasource
    }

    }

    Thursday, May 2, 2019 5:38 AM

Answers

All replies

  • User1120430333 posted

    An abstract class is a class that can't be instanced into an object. Another class can inherit from an abstract class and use the methods/behavior of an abstract class. An interface is a contract between the called/class object that the calling class/object where the calling class object can use the public properties and/or methods of the called class/object that implements the interface that allows communications between two classes/objects.. 

    An abstract example where all controllers in the MVC solution inherits from the Basecontroller that contains global exception handling in the Basecontroller. Any exception thrown in any code in a controller that inherits from the Basecontroller or code that a controller is using in another object, the exception is handled by the Basecontroller.

    The second thing that the Studentcontroller  class/object is using an IStudentmodels interface for the Studentmodels class/object that was instanced by the Unity IoC container, which is being dependency injected into the Studentcontroller.

    Usage of an interface promotes loose coupling..

    https://www.c-sharpcorner.com/blogs/understanding-interfaces-via-loose-coupling-and-tight-coupling

    https://www.c-sharpcorner.com/UploadFile/85ed7a/dependency-injection-in-C-Sharp/

    https://www.tutorialsteacher.com/ioc

    https://ardalis.com/new-is-glue

    using System;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    using log4net;
    
    namespace MVC.Controllers
    {
        public abstract partial class BaseController : Controller
        {
            private ILog _logger;
    
            protected BaseController()
            {
                _logger =  LogManager.GetLogger(typeof(BaseController));
            }
    
            protected override void OnException(ExceptionContext filterContext)
            {
                AppException appException = new AppException(Convert.ToString(filterContext.Exception))
                {
                    Type = filterContext.GetType().ToString(),
                    StackTrace = filterContext.Exception.StackTrace,
                    Source = filterContext.Exception.Source,
                    InnerException = Convert.ToString(filterContext.Exception.InnerException)
                };
    
                _logger.Error(appException.ToString());
    
                Server.ClearError();
    
                RedirectToControllers("Home", "Error");
            }
    
            private void RedirectToControllers(string control, string action)
            {
                var routeData = new RouteData();
    
                routeData.Values["controller"] = control;
    
                routeData.Values["action"] = action;
    
                IController controller = new HomeController();
    
                ((IController) controller).Execute(new RequestContext(
                    new HttpContextWrapper(System.Web.HttpContext.Current), routeData));
            }
        }
    }
    using System.Web.Mvc;
    using MVC.Models;
    
    namespace MVC.Controllers
    {
        [Authorize]
        public class StudentsController : BaseController  
        {
            private IStudentModels studmods;
            public StudentsController(IStudentModels studentModels)
            {
                studmods = studentModels;
            }
    
            // GET: Students
    
            [AllowAnonymous]
            public ActionResult Index()
            {
                return View(studmods.GetStudents());
            }
    
            //[AllowAnonymous]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(studmods.GetStudentById(id));
            }
            public ActionResult Create()
            {
                return View(studmods.Create());
            }
    
            [HttpPost]
            public ActionResult Create(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Create(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
    
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(studmods.Edit(id));
            }
    
            [HttpPost]
            public ActionResult Edit(StudentViewModels.Student student)
            {
                if (ModelState.IsValid)
                {
                    studmods.Edit(student);
                    return RedirectToAction("Index");
                }
    
                return View(student);
            }
    
            public ActionResult Delete(int id = 0 )
            {
                if (id > 0) studmods.Delete(id);
                
                return RedirectToAction("Index");
             }
        }
    }
    using System.Collections.Generic;
    
    namespace MVC.Models
    {
        public interface IStudentModels
        {
            StudentViewModels GetStudents();
            StudentViewModels.Student GetStudentById(int id);
            StudentViewModels.Student Create();
            void Create(StudentViewModels.Student student);
            StudentViewModels.Student Edit(int id);
            void Edit(StudentViewModels.Student student);
            void Delete(int id);
        }
    }
    ========================================================================================
    using System.Collections.Generic;
    using Entities;
    using WebAPI.Controllers;
    
    namespace MVC.Models
    {
        public class StudentModels : IStudentModels
        {
            private IStudentControllerAPI studapi;
            public StudentModels(IStudentControllerAPI studentControllerApi)
            {
                studapi = studentControllerApi;
            }
    
            public StudentViewModels GetStudents()
            {
                var dtos = studapi.GetStudents();
               
                var vm = new StudentViewModels {Students = new List<StudentViewModels.Student>()};
    
                foreach (var dto in dtos)
                {
                    var student = new StudentViewModels.Student
                    {
                        StudentID = dto.StudentID,
                        LastName = dto.LastName,
                        FirstName = dto.FirstName,
                        EnrollmentDate = dto.EnrollmentDate
                    };
    
                    vm.Students.Add(student);
                }
    
                return vm;
            }
    
            public StudentViewModels.Student GetStudentById(int id)
            {
                var dto = studapi.GetStudentById(id);
    
                var student = new StudentViewModels.Student
                {
                    StudentID = dto.StudentID,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName,
                    EnrollmentDate = dto.EnrollmentDate,
                    EnrollsandCourses = new List<EnrollandCourseViewModel.EnrollandCourse>()
                };
    
                foreach (var dtoec in dto.EnrollsandCourses)
                {
                    var ec = new EnrollandCourseViewModel.EnrollandCourse
                    {
                        Credits = dtoec.Credits,
                        Grade = dtoec.Grade,
                        Title = dtoec.Title
                    };
    
                    student.EnrollsandCourses.Add(ec);
                }
    
                return student;
            }
    
            public StudentViewModels.Student Create()
            {
                var student = new StudentViewModels.Student();
    
                return student;
            }
    
            public void Create(StudentViewModels.Student student)
            {
                var dto = new DTOStudent
                {
                    StudentID = student.StudentID,
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    EnrollmentDate = student.EnrollmentDate
                };
    
                studapi.CreateStudent(dto);
            }
    
            public StudentViewModels.Student Edit(int id)
            {
                var dto = studapi.GetStudentById(id);
    
                var student = new StudentViewModels.Student
                {
                    StudentID = dto.StudentID,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName,
                    EnrollmentDate = dto.EnrollmentDate
                };
    
                return student;
            }
    
            public void Edit(StudentViewModels.Student student)
            {
                var dto = new DTOStudent
                {
                    StudentID = student.StudentID,
                    FirstName = student.FirstName,
                    LastName = student.LastName,
                    EnrollmentDate = student.EnrollmentDate
                };
    
                studapi.UpdateStudent(dto);
            }
    
            public void Delete(int id)
            {
                studapi.DeleteStudent(id);
            }
        }
    }

    Thursday, May 2, 2019 7:51 AM
  • User-471420332 posted

    I am talking about simple example, i dont know MVC, I know only web forms

    Thursday, May 2, 2019 8:09 AM
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 2, 2019 8:14 AM
  • User1120430333 posted

    I am talking about simple example, i dont know MVC, I know only web forms

    It has nothing to do with MVC, which is just a platform where abstract and an Interface are being used. It's about Object Oriented Programming 101 and understanding the two OO concepts in actions..

    I am showing you a simple real world example of how and when you would use an abstract class and a class that implements an Interface and why.

    I am not showing you dogs and cats, but here you go.  

    https://www.guru99.com/c-sharp-abstract-class.html

    https://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface

    Thursday, May 2, 2019 9:14 AM